﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Transactions;
using MINERP.BLL.Common;
using MINERP.COM;
using MINERP.DAL;
using MINERP.DAL.CommonDAL;
using MINERP.DAL.DisJoin;
using MINERP.MODEL.DisjoinProForOutShop;
using MINERP.MODEL.FoundationModel;
using MINERP.MODEL.OverOrder;
using System.Data.Objects;
using System.Data.Common;
using MINERP.BLL.CustomerManage;


namespace MINERP.BLL.DisjoinProForOutShop
{
    public class DisJoinBLL2_Fuji
    {
        private WorkFlowListBLL _wflBll;
        private newSampleYPDBEntities dataBase = null;
        private DisJoinDAL _dal;

        public DisJoinBLL2_Fuji()
        {
            _wflBll = new WorkFlowListBLL();
            dataBase = new newSampleYPDBEntities();
            _dal = new DisJoinDAL();

        }

        /// <summary>
        /// 得到所有商户分堆格子
        /// </summary>
        /// <returns></returns>
        public List<ShopGrid_Info> GetAllShopGrid(out GridSubArea_Info subArea)
        {
            List<ShopGrid_Info> listShopGrid = new List<ShopGrid_Info>();
            int intShopType = (int)SubAreaType.Shop;
            GridSubArea shopSubArea = dataBase.GridSubArea.FirstOrDefault(p => p.Type == intShopType);
            subArea = new GridSubArea_Info() { HeightNum = shopSubArea.heightNum, WidthNum = shopSubArea.widthNum, SubAreaName = shopSubArea.SubAreaName };
            if (!shopSubArea.Grid.IsLoaded)
            {
                shopSubArea.Grid.Load();
            }
            //dataBase.
            foreach (var grid in shopSubArea.Grid)
            {
                listShopGrid.Add(ConvertShopGrid(grid));
            }

            return listShopGrid.OrderBy(p => Convert.ToInt32(p.GridName.Substring(1))).ToList();
        }

        /// <summary>
        /// 得到所有的委外加工商的格子
        /// </summary>
        /// <returns></returns>
        public List<OutShopGrid_Info> GetAllOutShopGrid(out GridSubArea_Info subArea)
        {
            List<OutShopGrid_Info> listOutShopGrid = new List<OutShopGrid_Info>();

            int intSubAreaType = (int)SubAreaType.OutShop;
            GridSubArea outShopSubArea = dataBase.GridSubArea.FirstOrDefault(p => p.Type == intSubAreaType);

            subArea = new GridSubArea_Info() { HeightNum = outShopSubArea.heightNum, WidthNum = outShopSubArea.widthNum, SubAreaName = outShopSubArea.SubAreaName };
            if (!outShopSubArea.Grid.IsLoaded)
            {
                outShopSubArea.Grid.Load();
            }

            foreach (var grid in outShopSubArea.Grid)
            {
                listOutShopGrid.Add(ConvertOutShopGrid(grid));
            }
            return listOutShopGrid.OrderBy(p => Convert.ToInt32(p.GridName.Substring(1))).ToList();
        }


        /// <summary>
        /// 得到商户格子里的详情和产品列表
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public List<OverOrderView> GetShopGridProductList(Grid_Info grid)
        {
            List<OverOrderView> listDetail = new List<OverOrderView>();

            Grid g = dataBase.Grid.FirstOrDefault(p => p.GridId == grid.GridId);
            dataBase.Refresh(RefreshMode.StoreWins, g.GridRecord);
            g.GridRecord.Load();
            //if (!g.GridRecord.IsLoaded)
            //{
            //    g.GridRecord.Load();
            //}
            decimal shopCurBalance = 0;
            Shop curShop = dataBase.Shop.FirstOrDefault(s => s.ShopId == grid.SomeId);
            if (curShop != null)
            {
                shopCurBalance = curShop.Balance ?? 0;
            }
            decimal totalCount = 0;
            List<GridRecord> delRecord = new List<GridRecord>();
            foreach (var gRecord in g.GridRecord)
            {
                OverOrderView gdb = GetGridDetailBaseFromOrderinfo2(dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == gRecord.SomeId), gRecord.OperateUid);
                if (gdb.OrderProductInfo == null)//即该产品已经打印了，但信息还留在格子中即要将格子信息清理掉
                {
                    delRecord.Add(gRecord);
                    continue;
                }
                if (gdb.OrderProductInfo.PrePriceCount + totalCount <= shopCurBalance)
                {
                    gdb.PreCountIsEnough = true;
                    totalCount += gdb.OrderProductInfo.PrePriceCount;
                }
                else
                {
                    gdb.PreCountIsEnough = false;
                }
                listDetail.Add(gdb);
            }
            if (delRecord.Count > 0)
            {
                foreach (var gt in delRecord)
                {
                    dataBase.DeleteObject(gt);
                }
                dataBase.SaveChanges();
            }

            return listDetail;
        }
        /// <summary>
        /// 转化列表
        /// </summary>
        /// <param name="orderinfo"></param>
        /// <returns></returns>
        private GridDetailBase GetGridDetailBaseFromOrderinfo(orderInfo orderinfo)
        {

            GridDetailBase orderView;
            if (orderinfo == null)
            {
                return new GridDetailBase();
            }
            if (!orderinfo.Tb_OrderBagReference.IsLoaded)//定单包
            {
                orderinfo.Tb_OrderBagReference.Load();
            }
            if (!orderinfo.Tb_OrderBag.usersReference.IsLoaded)//开单人
            {
                orderinfo.Tb_OrderBag.usersReference.Load();
            }
            if (!orderinfo.Tb_ProductReference.IsLoaded)//产品
            {
                orderinfo.Tb_ProductReference.Load();
            }
            if (!orderinfo.Tb_OrderBag.ShopReference.IsLoaded)//商户
            {
                orderinfo.Tb_OrderBag.ShopReference.Load();
            }

            if (!orderinfo.OutProcessRecord.IsLoaded)
            {
                orderinfo.OutProcessRecord.Load();
            }
            if (!orderinfo.photoInfo.IsLoaded)
            {
                orderinfo.photoInfo.Load();
            }


            orderView = new OverOrderView();
            //orderinfo.Tb_Product.tb_ProductTypeReference.Load();
            orderView.IsPrint = true;
            orderView.photoNum = orderinfo.photoInfo.Count;
            orderView.OrderProductInfo = new OrderInfo_Info() { ShopName = orderinfo.Tb_OrderBag.Shop.shopName, CompleteTime = orderinfo.CompleteTime, CtmName = orderinfo.CtmName, Height = orderinfo.Height, IsEdit = orderinfo.IsEdit, OrderPath = orderinfo.OrderPath, OrderProductCode = orderinfo.OrderProductCode, OrderProductId = orderinfo.OrderProductId, OrderProductName = orderinfo.OrderProductName, OrilOrderPath = orderinfo.OrilOrderPath, PageNum = orderinfo.PageNum, ProductNum = orderinfo.productNum, Remark = orderinfo.Remark, Status = orderinfo.status, Width = orderinfo.Width };
            orderView.OrderBagInfo = new Tb_OrderBag_Info() { BagCode = orderinfo.Tb_OrderBag.BagCode, ShopID = orderinfo.Tb_OrderBag.Shop.ShopId, BagName = orderinfo.Tb_OrderBag.BagName, CompleteTime = orderinfo.Tb_OrderBag.CompleteTime, FetchTime = orderinfo.Tb_OrderBag.FetchTime, OrderBagId = orderinfo.Tb_OrderBag.OrderBagId, OrderTime = orderinfo.Tb_OrderBag.OrderTime, Priority = orderinfo.Tb_OrderBag.Priority, Remark = orderinfo.Tb_OrderBag.Remark, ShopName = orderinfo.Tb_OrderBag.Shop.shopName, Status = orderinfo.Tb_OrderBag.Status, Type = orderinfo.Tb_OrderBag.Type, UserID = orderinfo.Tb_OrderBag.users.userID, };
            orderView.ProductInfo = new Tb_Product_Info() { ProuctId = orderinfo.Tb_Product.ProuctId, Height = orderinfo.Tb_Product.Height, PageNum = orderinfo.Tb_Product.PageNum, ProductName = orderinfo.Tb_Product.ProductName, ProductCode = orderinfo.Tb_Product.ProductCode, ProductDes = orderinfo.Tb_Product.ProductDes, Width = orderinfo.Tb_Product.Width };
            orderView.CreditLevel = orderinfo.Tb_OrderBag.Shop.CreditLevel.ToString();
            orderView.SaleMan = orderinfo.Tb_OrderBag.Shop.Salesman; ;

            return orderView;
        }
        /// <summary>
        /// 转化列表2添加操作员分片预分堆用
        /// </summary>
        /// <param name="orderinfo"></param>
        /// <returns></returns>
        private OverOrderView GetGridDetailBaseFromOrderinfo2(orderInfo orderinfo, int inOperateId)
        {

            OverOrderView orderView;
            if (orderinfo == null)
            {
                return new OverOrderView();
            }
            if (!orderinfo.Tb_OrderBagReference.IsLoaded)//定单包
            {
                orderinfo.Tb_OrderBagReference.Load();
            }
            if (!orderinfo.Tb_OrderBag.usersReference.IsLoaded)//开单人
            {
                orderinfo.Tb_OrderBag.usersReference.Load();
            }
            if (!orderinfo.Tb_ProductReference.IsLoaded)//产品
            {
                orderinfo.Tb_ProductReference.Load();
            }
            if (!orderinfo.Tb_OrderBag.ShopReference.IsLoaded)//商户
            {
                orderinfo.Tb_OrderBag.ShopReference.Load();
            }

            if (!orderinfo.OutProcessRecord.IsLoaded)
            {
                orderinfo.OutProcessRecord.Load();
            }
            if (!orderinfo.photoInfo.IsLoaded)
            {
                orderinfo.photoInfo.Load();
            }

            orderinfo.Tb_Product.tb_ProductTypeReference.Load();
            //orderinfo.Tb_Product.tb_ProductType.ProductTypeId

            orderView = new OverOrderView();
            if (orderinfo.Tb_Product.tb_ProductType.ProductTypeId == (int)OrderInfoProductType.NeedDesignProduct || orderinfo.Tb_Product.tb_ProductType.ProductTypeId == (int)OrderInfoProductType.NoNeedDesignProduct)
            {
                orderView.isShuChu = false;
            }
            else
            {
                orderView.isShuChu = true;
            }
            orderView.IsPrint = true;
            orderView.photoNum = orderinfo.photoInfo.Count;
            orderView.OrderProductInfo = new OrderInfo_Info() { ShopName = orderinfo.Tb_OrderBag.Shop.shopName, CompleteTime = orderinfo.CompleteTime, CtmName = orderinfo.CtmName, Height = orderinfo.Height, IsEdit = orderinfo.IsEdit, OrderPath = orderinfo.OrderPath, OrderProductCode = orderinfo.OrderProductCode, OrderProductId = orderinfo.OrderProductId, OrderProductName = orderinfo.OrderProductName, OrilOrderPath = orderinfo.OrilOrderPath, PageNum = orderinfo.PageNum, ProductNum = orderinfo.productNum, Remark = orderinfo.Remark, Status = orderinfo.status, Width = orderinfo.Width, PrePriceCount = orderinfo.PrePriceCount ?? 0, ProductType = orderinfo.ProductType };
            orderView.OrderBagInfo = new Tb_OrderBag_Info() { BagCode = orderinfo.Tb_OrderBag.BagCode, ShopID = orderinfo.Tb_OrderBag.Shop.ShopId, BagName = orderinfo.Tb_OrderBag.BagName, CompleteTime = orderinfo.Tb_OrderBag.CompleteTime, FetchTime = orderinfo.Tb_OrderBag.FetchTime, OrderBagId = orderinfo.Tb_OrderBag.OrderBagId, OrderTime = orderinfo.Tb_OrderBag.OrderTime, Priority = orderinfo.Tb_OrderBag.Priority, Remark = orderinfo.Tb_OrderBag.Remark, ShopName = orderinfo.Tb_OrderBag.Shop.shopName, Status = orderinfo.Tb_OrderBag.Status, Type = orderinfo.Tb_OrderBag.Type, UserID = orderinfo.Tb_OrderBag.users.userID };
            orderView.ProductInfo = new Tb_Product_Info() { Height = orderinfo.Tb_Product.Height, PageNum = orderinfo.Tb_Product.PageNum, ProductName = orderinfo.Tb_Product.ProductName, ProductCode = orderinfo.Tb_Product.ProductCode, ProductDes = orderinfo.Tb_Product.ProductDes, Width = orderinfo.Tb_Product.Width };
            orderView.CreditLevel = orderinfo.Tb_OrderBag.Shop.CreditLevel.ToString();
            orderView.SaleMan = orderinfo.Tb_OrderBag.Shop.Salesman; ;
            orderView.OperateID = inOperateId;
            if (inOperateId == -1)
            {
                orderView.IsPrint = false;
            }
            else
            {
                orderView.IsPrint = true;
            }
            return orderView;
        }
        /// <summary>
        /// 得到委外加工格子里的详情和产品列表
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public List<OverOrderView> GetOutShopGridProductList(Grid_Info grid)
        {
            OutProcessShop outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == grid.SomeId);
            return GetShopTaskViewByOutShopId(outShop.OutShopId);
        }
        /// <summary>
        /// 获得某个委外加工商的任务列表
        /// </summary>
        /// <param name="OutShopId">委外加工商ID</param>
        /// <returns></returns>
        public List<OverOrderView> GetShopTaskViewByOutShopId(int outShopId)
        {
            if (outShopId < 1)
            {
                return null;
            }
            else
            {

                int intInGrid = (int)OutProcessRecordStatus.InGrid;

                int orderDongStatus = (int)OrderInfoStatus.Doing;
                List<OutProcessRecord> recordList = dataBase.OutProcessRecord.Where(p => p.OutProcessShop.OutShopId == outShopId && p.Status == intInGrid && p.orderInfo.status == orderDongStatus).ToList();
                if (recordList.Count < 1)
                {
                    return null;
                }
                else
                {
                    List<orderInfo> orderList = new List<orderInfo>();
                    foreach (var record in recordList)
                    {
                        if (!record.orderInfoReference.IsLoaded)
                        {
                            record.orderInfoReference.Load();
                        }
                        orderList.Add(record.orderInfo);
                    }

                    return GetOverViewFromModel(orderList);
                }
            }
        }
        /// <summary>
        /// 将OrderInfo实体列表封装成OverOrderView对象
        /// </summary>
        /// <param name="orderList"></param>
        /// <returns></returns>
        private List<OverOrderView> GetOverViewFromModel(List<orderInfo> orderList)
        {
            List<OverOrderView> listView = new List<OverOrderView>();
            OverOrderView orderView;
            foreach (var orderinfo in orderList)
            {
                orderView = (OverOrderView)GetGridDetailBaseFromOrderinfo(orderinfo);
                orderView.IsPrint = false;
                orderView.InGrid = false;
                if (orderinfo.OutProcessRecord.Count > 0)
                {
                    OutProcessRecord opr = orderinfo.OutProcessRecord.First();
                    if (!opr.OutProcessShopReference.IsLoaded)
                    {
                        opr.OutProcessShopReference.Load();
                    }
                    if (!opr.usersReference.IsLoaded)//FetchUser
                    {
                        opr.usersReference.Load();
                    }
                    if (!opr.users1Reference.IsLoaded)//createUser
                    {
                        opr.users1Reference.Load();
                    }
                    if (opr.Status == (int)OutProcessRecordStatus.InGrid)
                    {
                        orderView.IsPrint = true;
                        orderView.InGrid = true;
                    }
                    orderView.OutRecordInfo = new OutProcessRecord_Info() { OutProcessRecordId = opr.OutProcessRecordId, CreateTime = opr.CreateTime, CreateUser = opr.users1.UserName, FetchUser = opr.users1.UserName, FetchRemark = opr.FetchRemark, FetchTime = (opr.FetchTime == null) ? DateTime.Now : (DateTime)opr.FetchTime, OutRemark = opr.OutRemark, PreFetchTime = opr.PreFetchTime, Status = opr.Status, OutShopInfo = new OutProcessShop_Info() { OutShopId = opr.OutProcessShop.OutShopId, OutShopName = opr.OutProcessShop.OutShopName } };
                }
                else
                {
                    orderView.OutRecordInfo = new OutProcessRecord_Info();
                    orderView.OutRecordInfo.OutShopInfo = new OutProcessShop_Info();
                }

                listView.Add(orderView);
            }

            return listView;
        }
        /// <summary>
        /// 得到委外加工格子里的详情和产品列表
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public List<OverOrderView> GetOutShopGridProductListForList(Grid_Info grid)
        {
            OutProcessShop outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == grid.SomeId);
            return GetShopTaskViewByOutShopIdForList(outShop.OutShopId);
        }
        /// <summary>
        /// 获得某个委外加工商的任务列表
        /// </summary>
        /// <param name="OutShopId">委外加工商ID</param>
        /// <returns></returns>
        public List<OverOrderView> GetShopTaskViewByOutShopIdForList(int outShopId)
        {
            if (outShopId < 1)
            {
                return null;
            }
            else
            {
                int status1 = (int)OutProcessRecordStatus.OutWaitFenDui;
                int status2 = (int)OutProcessRecordStatus.InGrid;
                int orderDongStatus = (int)OrderInfoStatus.Doing;
                List<OutProcessRecord> recordList = dataBase.OutProcessRecord.Where(p => p.OutProcessShop.OutShopId == outShopId && (p.Status == status1 || p.Status == status2) && p.orderInfo.status == orderDongStatus).ToList();
                if (recordList.Count < 1)
                {
                    return null;
                }
                else
                {
                    List<orderInfo> orderList = new List<orderInfo>();
                    foreach (var record in recordList)
                    {
                        if (!record.orderInfoReference.IsLoaded)
                        {
                            record.orderInfoReference.Load();
                        }
                        orderList.Add(record.orderInfo);
                    }

                    return GetOverViewFromModel(orderList);
                }
            }
        }


        /// <summary>
        /// 扫描条码后BLL总的接收
        /// </summary>
        /// <param name="barCode"></param>
        /// <param name="OperateUid"></param>
        public Grid_Info ReceiveBarCode(string barCode, int OperateUid, int techId, out SubAreaType gridType)
        {
            orderInfo oi = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductCode == barCode);

            if (oi == null)
            {
                throw new CustomMsgException("产品已完成，具体情况请查询客服！");

            }
            users OperateUser = dataBase.users.FirstOrDefault(p => p.userID == OperateUid);
            gridType = SubAreaType.Photo;

            if (oi.status != (int)OrderInfoStatus.Doing)
            {
                dataBase.Refresh(RefreshMode.StoreWins, oi);
            }
            if (oi.status != (int)OrderInfoStatus.Doing)
            {

                //return null;//提示扫描的条码不正确
                switch ((OrderInfoStatus)oi.status)
                {

                    case OrderInfoStatus.Error: throw new CustomMsgException("该产品有错误,具体情况请查询客服！");
                        break;
                    case OrderInfoStatus.Stop: throw new CustomMsgException("该产品是已停止,具体情况请查询客服！");
                        break;
                    case OrderInfoStatus.Completed: throw new CustomMsgException("产品是已完成,具体情况请查询客服！");
                        break;
                    default: throw new CustomMsgException("该产品无法处理,具体情况请查询客服！");
                        break;
                }

            }
            else
            {
                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                else
                {
                    oi.WorkOrderFlowList.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                }
                WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == (int)OrderFlowListStatus.Useable);
                if (wfl == null)
                {
                    throw new CustomMsgException("此产品还未到达本岗位,没有找到状态为1的结点！（可能是没有刷新，新重启程序）");
                }
                else
                {
                    if (!wfl.tb_TechReference.IsLoaded)
                    {
                        wfl.tb_TechReference.Load();
                    }
                    if (wfl.tb_Tech.TechId == techId)
                    {
                        //调用商户分堆模块
                        gridType = SubAreaType.Shop;
                        return AssignShopGrid(oi, OperateUser);
                    }
                    else
                    {
                        if (!oi.OutProcessRecord.IsLoaded)
                        {
                            oi.OutProcessRecord.Load();
                        }
                        else
                        {
                            dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi.OutProcessRecord);
                        }
                        if (oi.OutProcessRecord.Count < 1)
                        {
                            dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi.OutProcessRecord);
                            oi.OutProcessRecord.Load();
                        }
                        if (oi.OutProcessRecord.Count < 1)
                        {
                            int outShopType = (int)SubAreaType.OutShop;
                            //string strGridName = dataBase.Grid.FirstOrDefault(p => p.SomeId == oi.OrderProductId && p.GridSubArea.Type == outShopType).GridName;
                            //string strGridName = _dal.GetOutGridName(oi.OrderProductId);
                            //if (strGridName == null)
                            //{
                            throw new CustomMsgException("没有找到此产品的相关委外记录,请先分配委外商再扫描进格!");
                            //}
                            //else
                            //{
                            //    throw new CustomMsgException("请将该产品放到" + strGridName + "格子中!");
                            //}
                        }
                        else
                        {
                            if (wfl.tb_Tech.TechType != (int)TechType.OutProduct)
                            {
                                throw new CustomMsgException("该产品未到本岗位，请到客服产看该产品信息!");

                            }
                            if (oi.OutProcessRecord == null)
                            {
                                throw new CustomMsgException("在委外记录表中未找到此产品的相关的委外的记录!");

                            }

                            OutProcessRecord opr = oi.OutProcessRecord.FirstOrDefault(op => op.Status == (int)OutProcessRecordStatus.Outing || op.Status == (int)OutProcessRecordStatus.OutWaitFenDui || op.Status == (int)OutProcessRecordStatus.InGrid);
                            if (opr == null)
                            {
                                OutProcessRecord errOutRecord = oi.OutProcessRecord.FirstOrDefault(p => p.Status == (int)OutProcessRecordStatus.Fetched);
                                if (errOutRecord != null)
                                {
                                    errOutRecord.Status = (int)OutProcessRecordStatus.Outing;
                                    dataBase.SaveChanges();
                                    throw new CustomMsgException("请再试一次!");

                                }
                                int outShopType = (int)SubAreaType.OutShop;
                                // Grid grid = dataBase.Grid.FirstOrDefault(p => p.SomeId == oi.OrderProductId && p.GridSubArea.Type == outShopType);
                                string strGridName = _dal.GetOutGridName(oi.OrderProductId);
                                if (strGridName == null)
                                {
                                    throw new CustomMsgException("在委外记录表中未找到此产品的相关的委外的记录（状态为outing或是outWaitFenDui的记录）!");

                                }
                                else
                                {
                                    throw new CustomMsgException("请将该产品放到" + strGridName + "格子中!");
                                }

                            }
                            else
                            {
                                ////工厂端完成要完了才调用分堆模块
                                if (opr.Status == (int)OutProcessRecordStatus.Outing)
                                {
                                    //if (opr.Status2 == (int)OutProcessRecordStatus2.Complete)
                                    //{
                                    //调用收件确认流程
                                    if (!FetchAndSure(oi, OperateUser, wfl.tb_Tech.TechId, opr))
                                    {
                                        throw new CustomMsgException("收件确认出错，请重试!");
                                    }
                                    else
                                    {
                                        if (CheckOrderInfoTech(oi, techId))
                                        {
                                            //调用商户分堆
                                            gridType = SubAreaType.Shop;
                                            return AssignShopGrid(oi, OperateUser);
                                        }
                                        else
                                        {
                                            //提示用户此产品现在应处于哪个结点
                                            tb_Tech tt = GetOrderInfoEnabelTechInfo(oi);
                                            if (tt == null)
                                            {
                                                throw new CustomMsgException("产品流程错误,请检查该产品是否此完成!");
                                            }
                                            throw new CustomMsgException("此产品还未到本岗位，请将此产品送到:" + tt.TechName + "岗位");
                                        }
                                    }
                                    //}
                                    //else
                                    //{
                                    //    throw new CustomMsgException("此产品已打印委外单，正在外加工中！");
                                    //}
                                }
                                else if (opr.Status == (int)OutProcessRecordStatus.InGrid)
                                {
                                    //就直接报出格子名
                                    string strGridName = _dal.GetOutGridName(oi.OrderProductId);
                                    throw new CustomMsgException("请将该产品放到" + strGridName + "格子中2!");

                                }
                                else //(opr.Status == (int)OutProcessRecordStatus.OutWaitFenDui),调用委外分堆模块
                                {
                                    //调用委外商户分堆模块
                                    gridType = SubAreaType.OutShop;
                                    return AssignOutShopGrid(opr, OperateUser, oi);
                                }
                            }
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 清空格子
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public bool ClearGrid(Grid_Info grid)
        {

            Grid g = dataBase.Grid.FirstOrDefault(p => p.GridId == grid.GridId);
            if (!g.GridSubAreaReference.IsLoaded)
            {
                g.GridSubAreaReference.Load();
            }
            SubAreaType gridType = (SubAreaType)g.GridSubArea.Type;

            switch (gridType)
            {
                case SubAreaType.Shop: return ClearShopGrid(g);

                case SubAreaType.OutShop: return ClearOutShopGrid(g);

                default: return false;
            }
        }

        public SubAreaType GetGridTypeByGridId(Grid_Info grid)//得到格子的TYPE
        {
            Grid g = dataBase.Grid.FirstOrDefault(p => p.GridId == grid.GridId);
            if (!g.GridSubAreaReference.IsLoaded)
            {
                g.GridSubAreaReference.Load();
            }
            return (SubAreaType)g.GridSubArea.Type;
        }

        #region helper methods

        private bool ClearShopGrid(Grid shopGrid)
        {
            try
            {
                shopGrid.GridRecord.Load();
                List<GridRecord> deleteList = shopGrid.GridRecord.ToList();
                foreach (GridRecord record in deleteList)
                {
                    dataBase.DeleteObject(record);
                }

                shopGrid.Status = (int)GridStatus.useAble;
                shopGrid.SomeId = 0;
                dataBase.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private bool ClearOutShopGrid(Grid outShopGrid)
        {
            int outShopID = outShopGrid.SomeId;
            if (ClearShopGrid(outShopGrid))
            {
                OutProcessShop outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == outShopID);
                try
                {
                    if (!outShop.OutProcessRecord.IsLoaded)
                    {
                        outShop.OutProcessRecord.Load();
                    }
                    else
                    {
                        outShop.OutProcessRecord.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                    }
                    foreach (var item in outShop.OutProcessRecord.Where(op => op.Status == (int)OutProcessRecordStatus.InGrid))
                    {
                        item.Status = (int)OutProcessRecordStatus.OutWaitFenDui;
                    }
                    outShopGrid.SomeId = 0;
                    outShopGrid.Status = (int)GridStatus.useAble;
                    dataBase.SaveChanges();

                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 当Grid更改为Grid_Info
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private ShopGrid_Info ConvertShopGrid(Grid grid)
        {

            Shop shop = null;
            if (grid.Status == (int)GridStatus.use)
            {
                shop = dataBase.Shop.FirstOrDefault(p => p.ShopId == grid.SomeId);
            }
            Tb_OrderBag orderBag = null;
            if (shop == null)
            {
                orderBag = dataBase.Tb_OrderBag.FirstOrDefault(p => p.OrderBagId == grid.SomeId);
                if (orderBag != null)
                {
                    if (!orderBag.ShopReference.IsLoaded)
                    {
                        orderBag.ShopReference.Load();
                    }
                    shop = orderBag.Shop;
                }
            }

            ShopGrid_Info gridInfo = new ShopGrid_Info() { FirstEnterTime = grid.FirstEnterTime, GridId = grid.GridId, GridName = grid.GridName, SomeId = grid.SomeId, TempStatus = GetGridStatus(grid), Status = (int)grid.Status, GridType = grid.GridType };

            if (shop != null)
            {

                if (orderBag != null)
                {
                    gridInfo.Shop = new Shop_Info()
                    {
                        ShopId = orderBag.OrderBagId,
                        ShopName = orderBag.BagName,
                        ShopKeeper = "",
                        Address = "",
                        Tel1 = "",
                        Tel2 = "",
                        Balance = 0,
                        Remark = ""
                    };
                    if (!grid.GridRecord.IsLoaded)
                    {
                        grid.GridRecord.Load();

                    }
                    if (!orderBag.orderInfo.IsLoaded)
                    {
                        orderBag.orderInfo.Load();
                    }
                    foreach (orderInfo info in orderBag.orderInfo)
                    {
                        gridInfo.CtmName += info.CtmName + ",";
                    }
                    gridInfo.OrderName = orderBag.Shop.shopName;
                    gridInfo.OrderEnterTime = orderBag.OrderTime;
                    int allNum = orderBag.orderInfo.Where(o => o.status == 1).Count();
                    if (grid.GridRecord.Count(p => p.OperateUid != -1) == allNum)
                    {
                        gridInfo.IsComplete = true;//按客人（tborderbagid）分主动提示完成
                        gridInfo.AllNum = gridInfo.InNum = allNum;
                    }
                    else
                    {
                        gridInfo.AllNum = allNum;
                        gridInfo.InNum = grid.GridRecord.Count();
                    }
                   
                }
                else
                {
                    gridInfo.Shop = new Shop_Info()
                    {
                        ShopId = shop.ShopId,
                        ShopName = shop.shopName,
                        ShopKeeper = shop.shopKeeper,
                        Address = shop.address,
                        Tel1 = shop.Tel1,
                        Tel2 = shop.Tel2,
                        Balance = shop.Balance ?? 0,
                        Remark = shop.Remark
                    };
                      if (!grid.GridRecord.IsLoaded)
                    {
                        grid.GridRecord.Load();

                    }
                    gridInfo.InNum = grid.GridRecord.Count;
                    gridInfo.AllNum =
                        dataBase.orderInfo.Count(s => s.status == 1 && s.Tb_OrderBag.Shop.ShopId == shop.ShopId);
                    gridInfo.OrderEnterTime = grid.FirstEnterTime;
                }
            }
            return gridInfo;

        }
        /// <summary>
        /// 将Grid转化为OutShopGrid_Info
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private OutShopGrid_Info ConvertOutShopGrid(Grid grid)
        {
            OutProcessShop outShop = null;
            if (grid.Status == (int)GridStatus.use)
            {
                outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == grid.SomeId);
            }

            if (!grid.GridRecord.IsLoaded)
            {
                grid.GridRecord.Load();
            }
            int intInGrid = (int)OutProcessRecordStatus.InGrid;
            int intOrderDoingStatus = (int)OrderInfoStatus.Doing;
            int inGridNum = dataBase.OutProcessRecord.Where(op => op.Status == intInGrid && op.OutProcessShop.OutShopId == grid.SomeId && op.orderInfo.status == intOrderDoingStatus).Count();
            OutShopGrid_Info outgridInfo = new OutShopGrid_Info()
            {

                CurrentCount = inGridNum,
                FirstEnterTime = grid.FirstEnterTime,
                GridId = grid.GridId,
                GridName = grid.GridName,
            };

            if (outShop != null)
            {
                outgridInfo.SomeId = outShop.OutShopId;
                int intOutWaitFenDui = (int)OutProcessRecordStatus.OutWaitFenDui;
                outgridInfo.TotalCount = dataBase.OutProcessRecord.Where(op => (op.Status == intInGrid || op.Status == intOutWaitFenDui) && op.OutProcessShop.OutShopId == outShop.OutShopId && op.orderInfo.status == intOrderDoingStatus).Count();
                outgridInfo.OutShop = new OutProcessShop_Info()
                {
                    Addr = outShop.Addr,
                    City = outShop.City,
                    Code = outShop.Code,
                    Keeper = outShop.Keeper,
                    OutShopId = outShop.OutShopId,
                    OutShopName = outShop.OutShopName
                };
                outgridInfo.Status = (int)grid.Status;
            }
            outgridInfo.TempStatus = GetGridStatus(outgridInfo);
            return outgridInfo;
        }

        /// <summary>
        /// 更新格子里的信息判断格子的状态
        /// </summary>
        /// <param name="grid_info"></param>
        /// <returns></returns>
        private TempGridStatus GetGridStatus(OutShopGrid_Info grid_info)
        {
            if (grid_info.TotalCount == grid_info.CurrentCount)
            {
                return TempGridStatus.NumMatch;
            }
            else if (grid_info.FirstEnterTime.Subtract(DateTime.Now).Hours >= 0)
            {
                return TempGridStatus.OutTime;
            }
            else
            {
                return TempGridStatus.normal;
            }

        }
        /// <summary>
        /// 得到格子的是否超时的状态
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private TempGridStatus GetGridStatus(Grid grid)
        {
            if (grid.FirstEnterTime.Subtract(DateTime.Now).Hours >= 0)
            {
                return TempGridStatus.OutTime;
            }
            else
            {
                return TempGridStatus.normal;
            }
        }

        /// <summary>
        /// 分配委外商户格子
        /// </summary>
        /// <param name="opr"></param>
        /// <param name="operateUser"></param>
        /// <param name="oi"></param>
        /// <returns></returns>
        private Grid_Info AssignOutShopGrid(OutProcessRecord opr, users operateUser, orderInfo oi)
        {
            if (!opr.OutProcessShopReference.IsLoaded)
            {
                opr.OutProcessShopReference.Load();
            }
            OutProcessShop outShop = opr.OutProcessShop;

            Grid gd;
            try
            {
                gd = AssignGrid(SubAreaType.OutShop, outShop.OutShopId, oi.OrderProductId, operateUser);
                opr.Status = (int)OutProcessRecordStatus.InGrid;



                dataBase.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (gd == null)
            {
                throw new Exception("没有可用格子！");
            }
            return ConvertOutShopGrid(gd);
        }
        /// <summary>
        ///  分配格子--公用
        /// </summary>
        /// <param name="subType"></param>
        /// <param name="someId">shopid</param>
        /// <param name="operateUser"></param>
        /// <param name="gridRecordId">orderproductid</param>
        /// <returns></returns>
        private Grid AssignGrid(SubAreaType subType, int GridSomeId, int gridRecordSomeId, users operateUser)
        {
            //using (TransactionScope ts = new TransactionScope())
            //{
            try
            {
                int outShopType = (int)subType;
                GridSubArea gridSubArea = dataBase.GridSubArea.FirstOrDefault(p => p.Type == outShopType);


                if (!gridSubArea.Grid.IsLoaded)
                {
                    gridSubArea.Grid.Load();
                }
                else
                {
                    if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                    {
                        dataBase.Connection.Open();
                    }
                    dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, gridSubArea.Grid);
                }
                orderInfo oi = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == gridRecordSomeId);
                oi.Tb_OrderBagReference.Load();
                Tb_OrderBag orderbag = oi.Tb_OrderBag;
                int intUse = (int)GridStatus.use;
                int intUseAble = (int)GridStatus.useAble;
                Grid gd = gridSubArea.Grid.FirstOrDefault(g => g.Status == intUse && g.SomeId == GridSomeId);
                if (gd == null)//没有找到,分配新的
                {
                    gd = gridSubArea.Grid.Where(g => g.Status == intUseAble).OrderBy(g => Convert.ToInt32(g.GridName.Substring(1))).FirstOrDefault();
                    if (gd == null)
                    {
                        throw new Exception("格子已满,请先打印一些商户以提供空格子!");
                    }
                    else
                    {
                        gd.SomeId = GridSomeId;
                        gd.Status = (int)GridStatus.use;
                        //gd.FirstEnterTime = DateTime.Now;
                        gd.FirstEnterTime = orderbag.FetchTime;

                        if ((int)subType == (int)SubAreaType.Shop)
                        {
                            //if (!gd.GridRecord.IsLoaded)
                            //{
                            gd.GridRecord.Load();
                            //}
                            //else
                            //{
                            //    dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, gd.GridRecord);
                            //}
                            GridRecord gridRecord = gd.GridRecord.FirstOrDefault(gr => gr.SomeId == gridRecordSomeId);
                            if (gridRecord == null)
                            {
                                gd.GridRecord.Add(new GridRecord()
                                {
                                    CreateTime = CommonMethodDAL.GetServerTime(),
                                    Grid = gd,
                                    Num = 1,
                                    SomeId = gridRecordSomeId,
                                    OperateUid = operateUser.userID
                                });
                            }
                            else
                            {
                                gridRecord.OperateUid = operateUser.userID;//已经存在的产品
                                if (oi.productNum > gridRecord.Num)
                                {
                                    gridRecord.Num += 1;
                                }
                            }
                        }
                    }

                }
                else
                {
                    if (gd.FirstEnterTime.CompareTo(orderbag.FetchTime) > 0)
                    {
                        gd.FirstEnterTime = orderbag.FetchTime;
                    }
                    if ((int)subType == (int)SubAreaType.Shop)
                    {

                        gd.GridRecord.Load();

                        GridRecord gridRecord = gd.GridRecord.FirstOrDefault(gr => gr.SomeId == gridRecordSomeId);
                        if (gridRecord == null)
                        {
                            gd.GridRecord.Add(new GridRecord()
                            {
                                CreateTime = CommonMethodDAL.GetServerTime(),
                                Grid = gd,
                                Num = 1,
                                SomeId = gridRecordSomeId,
                                OperateUid = operateUser.userID
                            });
                        }
                        else
                        {
                            //gridRecord.
                            gridRecord.OperateUid = operateUser.userID;//已经存在的产品
                            if (oi.productNum > gridRecord.Num)
                            {
                                gridRecord.Num += 1;
                            }
                        }
                    }
                }

                dataBase.SaveChanges();
                //ts.Complete();
                return gd;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Closed)
                {
                    dataBase.Connection.Close();
                }
            }
            //}
        }

        /// <summary>
        /// 商户分堆模块
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="operateUser"></param>
        /// <returns></returns>
        private Grid_Info AssignShopGrid(orderInfo oi, users operateUser)
        {
            if (!oi.Tb_OrderBagReference.IsLoaded)
            {
                oi.Tb_OrderBagReference.Load();
            }
            if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
            {
                oi.Tb_OrderBag.ShopReference.Load();
            }
            Shop shop = oi.Tb_OrderBag.Shop;

            Grid gd;
            try
            {

                if (!shop.IsAssignByCustom)//按照商户分堆
                {
                    gd = AssignGrid(SubAreaType.Shop, shop.ShopId, oi.OrderProductId, operateUser);
                    gd.GridType = (int)GridType.Shop;
                }
                else//按照客人分堆，实际是按照订单包id（OrderBagId）
                {
                    gd = AssignGrid(SubAreaType.Shop, oi.Tb_OrderBag.OrderBagId, oi.OrderProductId, operateUser);

                    gd.GridType = (int)GridType.Custom;
                }

                //委外账单 修改状态

                if (gd != null && gd.GridId != 0)
                {
                    int intOutProduct = (int)OutProcessProductStatus.Received;

                    OutShopBillDetail detail = dataBase.OutShopBillDetail.FirstOrDefault(p => p.OrderProductCode == oi.OrderProductCode);
                    if (detail != null)
                    {


                        detail.ProductStatus = intOutProduct; //委外产品已经收到
                        detail.OutShop_BillReference.Load();
                        OutShop_Bill bill = detail.OutShop_Bill;
                        bill.OutShopBillDetail.Load();
                        List<OutShopBillDetail> list = bill.OutShopBillDetail.ToList();

                        int rectiveCount = list.Count(p => p.ProductStatus == intOutProduct);
                        decimal summedReceive = list.Where(p => p.ProductStatus == intOutProduct).Sum(p => p.UnitPrice * p.Num);
                        if (rectiveCount == list.Count())
                        {
                            bill.ProductSratus = (int)OutProcessProductStatus.Complete;
                        }
                        else
                        {
                            bill.ProductSratus = (int)OutProcessProductStatus.Received;
                        }


                        bill.SummedRecive = summedReceive;

                    }
                    else
                    {
                        //记录在日志中
                    }
                }

                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                foreach (WorkOrderFlowList orderFlowList in oi.WorkOrderFlowList)
                {
                    orderFlowList.tb_TechReference.Load();
                }
                int pbtechtype = (int) TechType.PrintBill;
                WorkOrderFlowList pbFlowList = oi.WorkOrderFlowList.FirstOrDefault(p => p.tb_Tech.TechType == pbtechtype);
                if (pbFlowList != null)
                {
                    pbFlowList.UserId = operateUser.userID;
                    pbFlowList.CompletedTime=DateTime.Now;
                }
                dataBase.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ConvertShopGrid(gd);
        }

        /// <summary>
        /// 收件确认模块
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="operateUser"></param>
        /// <returns></returns>
        private bool FetchAndSure(orderInfo oi, users operateUser, int techId, OutProcessRecord opr)
        {
            if (_wflBll.OverCurTech(techId, operateUser.userID, oi, dataBase))
            {
                opr.Status = (int)OutProcessRecordStatus.Fetched;
                opr.users1 = operateUser;
                //opr.FetchTime = DateTime.Now;
                opr.FetchRemark = "黙认收件"; //
                dataBase.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 检查给定orderinfo实体的当前流程状态为enable的结点是否与给点的结点ID相等
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="techId"></param>
        /// <returns>相等true,不等false</returns>
        private bool CheckOrderInfoTech(orderInfo oi, int techId)
        {
            tb_Tech tt = GetOrderInfoEnabelTechInfo(oi);
            if (tt == null || tt.TechId != techId)
            {
                return false;
            }
            else
            {
                return true;
            }

        }

        /// <summary>
        /// 找到OI当前可用的结点实体
        /// </summary>
        /// <param name="oi"></param>
        /// <returns></returns>
        private tb_Tech GetOrderInfoEnabelTechInfo(orderInfo oi)
        {
            if (!oi.WorkOrderFlowList.IsLoaded)
            {
                oi.WorkOrderFlowList.Load();
            }
            else
            {
                oi.WorkOrderFlowList.Load(System.Data.Objects.MergeOption.OverwriteChanges);
            }

            WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == (int)OrderFlowListStatus.Useable);
            if (wfl == null)
            {
                return null;
            }
            else
            {
                if (!wfl.tb_TechReference.IsLoaded)
                {
                    wfl.tb_TechReference.Load();
                }
                return wfl.tb_Tech;
            }
        }
        #endregion



        /// <summary>
        /// 得到委外商分区
        /// </summary>
        /// <returns></returns>
        public GridSubArea_Info GetOutShopSubArea()
        {
            int intOutShop = (int)SubAreaType.OutShop;
            GridSubArea area = dataBase.GridSubArea.FirstOrDefault(p => p.Type == intOutShop);

            GridSubArea_Info info = new GridSubArea_Info() { SubAreaID = area.SubAreaID, SubAreaName = area.SubAreaName, WidthNum = area.widthNum, HeightNum = area.heightNum, NameHeadChar = area.nameHeadChar, Type = area.Type, OutTimeAlarmTime = (double)area.OutTimeAlarmTime, GridClearTime = (double)area.GridClearTime };
            if (info == null)
            {
                return null;
            }
            return info;
        }

        /// <summary>
        /// 得到商户分区
        /// </summary>
        /// <returns></returns>
        public GridSubArea_Info GetShopSubArea()
        {
            int intShopType = (int)SubAreaType.Shop;
            GridSubArea area = dataBase.GridSubArea.FirstOrDefault(p => p.Type == intShopType);

            GridSubArea_Info info = new GridSubArea_Info() { SubAreaID = area.SubAreaID, SubAreaName = area.SubAreaName, WidthNum = area.widthNum, HeightNum = area.heightNum, NameHeadChar = area.nameHeadChar, Type = area.Type, OutTimeAlarmTime = (double)area.OutTimeAlarmTime, GridClearTime = (double)area.GridClearTime };
            if (info == null)
            {
                return null;
            }
            return info;
        }

        public void MakeSureOut(Grid_Info grid_Info, int userId)//确认委外,打印委外格子里的信息时,要处理的流程信息
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                try
                {
                    Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);
                    OutProcessShop outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == grid.SomeId);

                    int inGrid = (int)OutProcessRecordStatus.InGrid;
                    List<OutProcessRecord> listOPR = dataBase.OutProcessRecord.Where(p => p.OutProcessShop.OutShopId == outShop.OutShopId && p.Status == inGrid).ToList(); ;
                    foreach (var outRecord in listOPR)
                    {
                        if (!outRecord.orderInfoReference.IsLoaded)
                        {
                            outRecord.orderInfoReference.Load();
                        }
                        outRecord.Status = (int)OutProcessRecordStatus.Outing;
                        if (NextTechIsFactoryTech(dataBase, outRecord.orderInfo.OrderProductId))
                        {
                            int currentTech = GetCurrentTechIdByOrderProductId(outRecord.orderInfo.OrderProductId);
                            _wflBll.OverCurTech(currentTech, userId, outRecord.orderInfo.OrderProductId);
                        }
                    }
                    if (!grid.GridRecord.IsLoaded)
                    {
                        grid.GridRecord.Load();
                    }

                    List<GridRecord> records = grid.GridRecord.ToList();

                    foreach (GridRecord record in records)
                    {
                        dataBase.DeleteObject(record);
                    }

                    grid.Status = (int)GridStatus.useAble;
                    dataBase.SaveChanges();

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public void MakeSureOut(Grid_Info grid_Info, List<OverOrderView> selectOutRecords, out bool IsClearGrid, int userId)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {

                Grid grid = dataBase.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);

                OutProcessShop outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == grid.SomeId);

                int inGrid = (int)OutProcessRecordStatus.InGrid;
                int totalCount = dataBase.OutProcessRecord.Count(p => p.OutProcessShop.OutShopId == grid.SomeId && p.Status == inGrid);



                foreach (OverOrderView opr in selectOutRecords)
                {
                    OutProcessRecord or = dataBase.OutProcessRecord.First(op => op.OutProcessRecordId == opr.OutRecordId);
                    if (or != null)
                    {
                        or.Status = (int)OutProcessRecordStatus.Outing;
                    }
                    if (NextTechIsFactoryTech(dataBase, opr.OrderProductId))
                    {
                        int currentTech = GetCurrentTechIdByOrderProductId(opr.OrderProductId, dataBase);
                        bool ret = _wflBll.OverCurTech(currentTech, userId, opr.OrderProductId, dataBase);
                        if (!ret)
                        {
                            new Exception("流程修改失败，请查询产品状态是否正常！");
                        }
                    }
                }


                if (selectOutRecords.Count == totalCount)
                {
                    grid.Status = (int)GridStatus.useAble;
                    grid.SomeId = 0;

                    //if (!grid.GridRecord.IsLoaded)//从GridRecord表中删除相应的记当，其实这里只有一种记录
                    //{
                    //    grid.GridRecord.Load();
                    //}
                    //List<GridRecord> list = grid.GridRecord.ToList();
                    //foreach (var item in list)
                    //{
                    //    dataBase.DeleteObject(item);
                    //}
                    IsClearGrid = true;
                }
                else
                {
                    IsClearGrid = false;
                }

                dataBase.SaveChanges();
            }
        }

        /// <summary>
        /// 判断下一节点是不是工厂节点
        /// </summary>
        /// <param name="db"></param>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        private bool NextTechIsFactoryTech(newSampleYPDBEntities db, int orderProductId)
        {
            bool flag = false;

            List<WorkOrderFlowList> wflList = db.WorkOrderFlowList.Where(w => w.orderInfo.OrderProductId == orderProductId).OrderBy(w => w.WorkOrder).ToList();
            WorkOrderFlowList wfl = wflList.FirstOrDefault(w => w.Status == 1);
            if (wfl != null)//存在状态为1的节点
            {
                for (int i = 0; i < wflList.Count; i++)
                {
                    if (wfl.WorkFlowListId == wflList[i].WorkFlowListId)//当前所在节点
                    {
                        try
                        {
                            WorkOrderFlowList nextwfl = wflList[i + 1];
                            if (!nextwfl.tb_TechReference.IsLoaded)
                            {
                                nextwfl.tb_TechReference.Load();
                            }
                            if (nextwfl.tb_Tech.TechType == (int)TechType.Factory)//如果是工厂节点
                            {
                                flag = true;
                            }
                            else
                            {
                                flag = false;
                            }
                            break;
                        }
                        catch
                        {
                            flag = false;
                        }
                    }
                }
            }
            else
            {
                new Exception("产品已经完成！");
            }
            return flag;

        }

        /// <summary>
        /// 通过产品ID获得该产品的当前流程ID
        /// </summary>
        /// <param name="orderproductId"></param>
        /// <returns>0 产品不存在，-1 产品无流程或者流程已完成</returns>
        private int GetCurrentTechIdByOrderProductId(int orderproductId)
        {
            int ret;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderproductId);
                if (oi != null)//产品存在
                {
                    if (!oi.WorkOrderFlowList.IsLoaded)
                    {
                        oi.WorkOrderFlowList.Load();
                    }
                    WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == 1);
                    if (wfl != null)
                    {
                        if (!wfl.tb_TechReference.IsLoaded)
                        {
                            wfl.tb_TechReference.Load();
                        }
                        ret = wfl.tb_Tech.TechId;
                    }
                    else//产品无流程或者流程已完成
                    {
                        ret = -1;
                    }
                }
                else//产品不存在
                {
                    ret = 0;
                }
            }

            return ret;
        }
        private int GetCurrentTechIdByOrderProductId(int orderproductId, newSampleYPDBEntities db)
        {
            int ret;
            //using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            //{
            orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderproductId);
            if (oi != null)//产品存在
            {
                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == 1);
                if (wfl != null)
                {
                    if (!wfl.tb_TechReference.IsLoaded)
                    {
                        wfl.tb_TechReference.Load();
                    }
                    ret = wfl.tb_Tech.TechId;
                }
                else//产品无流程或者流程已完成
                {
                    ret = -1;
                }
            }
            else//产品不存在
            {
                ret = 0;
            }
            //}

            return ret;
        }
        public void MakeSureOutNew(Grid_Info grid_Info, List<OverOrderView> selectOutRecords, out bool IsClearGrid)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                Grid grid = db.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);
                OutProcessShop outShop = db.OutProcessShop.FirstOrDefault(p => p.OutShopId == grid.SomeId);

                int inGrid = (int)OutProcessRecordStatus.InGrid;
                int totalCount = db.OutProcessRecord.Count(p => p.OutProcessShop.OutShopId == grid.SomeId && p.Status == inGrid);



                foreach (OverOrderView opr in selectOutRecords)
                {
                    OutProcessRecord or = db.OutProcessRecord.First(op => op.OutProcessRecordId == opr.OutRecordId);
                    if (or != null)
                    {
                        or.Status = (int)OutProcessRecordStatus.Outing;
                    }
                }


                if (selectOutRecords.Count == totalCount)
                {
                    grid.Status = (int)GridStatus.useAble;
                    grid.SomeId = 0;

                    //if (!grid.GridRecord.IsLoaded)//从GridRecord表中删除相应的记当，其实这里只有一种记录
                    //{
                    //    grid.GridRecord.Load();
                    //}
                    //List<GridRecord> list = grid.GridRecord.ToList();
                    //foreach (var item in list)
                    //{
                    //    dataBase.DeleteObject(item);
                    //}
                    IsClearGrid = true;
                }
                else
                {
                    IsClearGrid = false;
                }

                db.SaveChanges();
            }
        }

        //public SHOP_Bill_Info OrderComplete(int curTechId, int operUid, Grid_Info grid_Info, bool isForcePrint)//发货,并生成帐单
        //{
        //    bool hasAllProd = false;
        //    Grid grid = dataBase.Grid.FirstOrDefault(g => g.GridId == grid_Info.GridId);
        //    dataBase.Refresh(RefreshMode.StoreWins, grid.GridRecord);//强制刷新。多人分堆用
        //    //if (!grid.GridRecord.IsLoaded)
        //    //{
        //    grid.GridRecord.Load();
        //    //}
        //    if (grid.GridRecord.Count == 0)
        //    {
        //        return null;
        //    }

        //    List<int> orderProductIdList = grid.GridRecord.Where(p => p.OperateUid != -1).Select(gr => gr.SomeId).ToList();
        //    if (orderProductIdList.Count == 0)
        //    {
        //        return null;
        //    }

        //    return OrderComplete(curTechId, operUid, grid_Info, orderProductIdList, out hasAllProd, isForcePrint,0);

        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="curTechId"></param>
        /// <param name="operUid"></param>
        /// <param name="grid_Info"></param>
        /// <param name="SelectOrderInfo"></param>
        /// <param name="hasAllProd">选中的要打印的产品是否是格子里的所有产品</param>
        /// inPay 垫付的运费体现在账单上
        /// <returns></returns>
        //public SHOP_Bill_Info OrderComplete(int curTechId, int operUid, Grid_Info grid_Info, List<GridDetailBase> SelectOrderInfo, out bool hasAllProd, bool isForcePrint, int inPay)
        //{
        //    hasAllProd = false;
        //    List<int> orderProductIdList = SelectOrderInfo.Select(p => p.OrderProductId).ToList();
        //    return OrderComplete(curTechId, operUid, grid_Info, orderProductIdList, out hasAllProd, isForcePrint, inPay);
        //}

        /*
        public SHOP_Bill_Info OrderComplete(int curTechId, int operUid, Grid_Info grid_Info, List<int> ListOrderProductId, out bool hasAllProd, bool hasForcibePrint, int inPay)
        {
            dataBase = new newSampleYPDBEntities();
            hasAllProd = false;                                 //结帐的是否是该格子中的全部产品，影响到前台是否需要清空相应的格子

            int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样


            int shopId = grid_Info.SomeId;                      //商户ID
            if (grid_Info.GridType == (int)GridType.Custom) 
            {
                //shopId = SelectOrderInfo.FirstOrDefault().OrderBagInfo.ShopID;
            }
            List<int> DonedOrderProudctId = new List<int>(ListOrderProductId); //能够正常结帐单的产品ID

            double Bill_Price = 0;                              //此帐单的总价格
            Shop curShop;                                       //当前商户
            Grid curGrid;                                       //当前格子

            SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
            SHOP_Bill sb = new SHOP_Bill();                     //用于向数库添加数据

            List<Tb_OrderBag> NeedMoveDataOrderList = new List<Tb_OrderBag>();//需要转移数据的定单包列表
            bool isNeedMoveData = false;
            bool isNeedOverOrderInfo = false;//是否需要完产品流程

            //初始信息
            sb.NeedDeliver = 1;                                 //是否需要配送   
            sb.Status = (int)ShopBillStatus.UnCheckOut;

            sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
            sbinfo.CreateTime = sb.CreateTime;//获取系统时间


            sbinfo.List_Detail = new List<Bill_Detail_Info>();


            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            {
                try
                {
                    curShop = dataBase.Shop.FirstOrDefault(p => p.ShopId == shopId);

                    #region 得到商户的帐单的顺序号

                    List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == shopId).ToList();
                    if (listShopBill.Count <= 0)
                    {
                        sb.BillOrderCode = 1;
                    }
                    else
                    {
                        sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                    }


                    //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                    sbinfo.BillOrderCode = sb.BillOrderCode;



                    #endregion

                    foreach (var orderProductId in ListOrderProductId)
                    {
                        isNeedOverOrderInfo = true;
                        #region 帐单名细--每一层，就是产品（orderinfo）

                        decimal orderInfoPrice = 0;//此产品的真实价格

                        orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                        if (oi.status == (int)OrderInfoStatus.Completed)
                        {
                            dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
                        }

                        #region 加载数据库
                        if (!oi.Tb_ProductReference.IsLoaded)
                        {
                            oi.Tb_ProductReference.Load();
                        }
                        if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                        {
                            oi.Tb_Product.tb_CostTypeReference.Load();
                        }
                        if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        {
                            oi.Tb_Product.Tb_PorductCategoryReference.Load();
                        }
                        if (!curShop.Shop_Product_Price.IsLoaded)
                        {
                            curShop.Shop_Product_Price.Load();
                        }
                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }


                        #endregion

                        Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName };
                        Bill_Detail_Id++;
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                        orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);
                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                        #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                        #region //对帐户金额的操作
                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                                #region
                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)orderInfoPrice)
                                {
                                    //如果余额不足，就判断是否有权限可打印此帐单
                                    if (hasForcibePrint)//可以强打
                                    {
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        curShop.Balance -= (decimal)orderInfoPrice;
                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "定单号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        dataBase.AddToShopBlanceCrushRecord(br);
                                    }
                                    else
                                    {
                                        oi.status = (int)OrderInfoStatus.WaitPay;
                                        curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                        isNeedOverOrderInfo = false;
                                        DonedOrderProudctId.Remove(oi.OrderProductId);
                                    }
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)orderInfoPrice;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "定单号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户 
                                #region
                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)orderInfoPrice;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "定单号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }

                        #endregion

                        if (isNeedOverOrderInfo)
                        {
                            bool result = _wflBll.OverCurTech(curTechId, operUid, oi, dataBase, out isNeedMoveData);

                            if (!result)
                            {
                                throw new CustomMsgException(oi.OrderProductCode + "请检查此产品是否被暂停，如未被暂停，请重启程序！" + "(节点:" + curTechId.ToString() + "操作员:" + operUid.ToString());
                            }
                            else
                            {
                                if (isNeedMoveData)
                                {
                                    NeedMoveDataOrderList.Add(oi.Tb_OrderBag);
                                }

                                #region//在此修改相应的业绩记录
                                double orderArea = -1;
                                List<New_EmployeePerformance> emList = dataBase.New_EmployeePerformance.Where(e => e.OrderproductId == oi.OrderProductId).ToList();
                                foreach (var em in emList)
                                {
                                    if (orderArea == -1)
                                    {
                                        orderArea = dbinfo.ListDetail_Detail.Where(bddt => bddt.Type == (int)Bill_Detail_Detail_Type.NeedStatArea).Sum(bddt => bddt.Area);
                                    }
                                    if (em != null)
                                    {
                                        em.OrderCount = orderInfoPrice;
                                        em.Status = (int)OrderInfoStatus.Completed;
                                        em.OrderConpletedTime = oi.CompleteTime;
                                        em.OrderArea = orderArea;
                                    }
                                }
                                #endregion

                                sb.Bill_Detail.Add(bd);

                                dbinfo.BillDetailId = Bill_Detail_Id;
                                sbinfo.List_Detail.Add(dbinfo);
                                Bill_Detail_Id++;
                                Bill_Price += (double)orderInfoPrice;
                            }
                        }

                        #endregion

                        #endregion
                    }
                    //添加运费项目
                    if (inPay > 0)
                    {
                        #region 收费项目
                        Bill_Detail bd = new Bill_Detail() { OiRemark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName };
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                        Bill_Detail_Id++;

                        bd.Bill_Detail_Detail.Add(new Bill_Detail_Detail()
                        {
                            Area = 0,
                            Count = inPay,
                            DetailName = "运费",
                            Num = 1,
                            Spec = "",
                            Type = 0,
                            UnitPrice = inPay
                        });

                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);

                        sb.Bill_Detail.Add(bd);

                        dbinfo.BillDetailId = Bill_Detail_Id;
                        sbinfo.List_Detail.Add(dbinfo);
                        Bill_Detail_Id++;
                        Bill_Price += (double)inPay;

                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                                #region
                                //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)inPay)//默认都是强大
                                {
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    curShop.Balance -= (decimal)inPay;
                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)inPay;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户 
                                #region
                                //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)inPay;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "运费:" + inPay + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }
                        #endregion 收费项目
                    }


                    #region 清除相应的格子信息

                    curGrid = dataBase.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);
                    if (!curGrid.GridRecord.IsLoaded)
                    {
                        curGrid.GridRecord.Load();
                    }
                    List<GridRecord> listRecord = curGrid.GridRecord.ToList();
                    foreach (var oId in DonedOrderProudctId)
                    {
                        GridRecord result = listRecord.Find(delegate(GridRecord gr)
                        {
                            if (gr.SomeId == oId)
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        });
                        if (result != null)
                        {
                            dataBase.DeleteObject(result);
                        }
                    }

                    if (listRecord.Count == DonedOrderProudctId.Count)
                    {
                        curGrid.Status = (int)GridStatus.useAble;
                        curGrid.SomeId = 0;
                        hasAllProd = true;
                    }
                    #endregion

                    //记录帐单信息            

                    sb.Shop = curShop;
                    sb.TotalPrice = (decimal)Math.Round(Bill_Price, 2);
                    sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel };
                    sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                    sbinfo.BillCount = Bill_Price;
                    if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                    {
                        if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                        {
                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                        }
                        else
                        {
                            sb.Status = (int)ShopBillStatus.CheckedOut;
                        }
                        sb.ShopBalance = curShop.Balance ?? 0;
                        dataBase.AddToSHOP_Bill(sb);

                        dataBase.SaveChanges();

                        ts.Complete();
                    }
                    else
                    {
                        sbinfo = null;
                        sb = null;
                    }


                    try
                    {
                        ////转移数据到历史记录表中,并删除相应的旧数据
                        //if (NeedMoveDataOrderList.Count > 0)
                        //{
                        //    Thread thMoveHistoryTable = new Thread(new ParameterizedThreadStart(ThMoveData));
                        //    thMoveHistoryTable.Start(NeedMoveDataOrderList);

                        //    statPhotoEffectAreaDelegate dlStat = new statPhotoEffectAreaDelegate(OrderInfoStatDAL.StatPhotoEffectArea);
                        //    dlStat.BeginInvoke(ListOrderProductId, null, null);
                        //}
                    }
                    catch (Exception ex)
                    {
                        WriteLogForCheck.WriteLogFile("在统计拼板面积或是移动历史数据时出错：" + ex.Message);
                    }
                    if (sbinfo != null)
                    {
                        sbinfo.BillId = sb.BillId;
                        sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                    }
                    return sbinfo;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
         */

        public SHOP_Bill_Info OrderComplete(int curTechId, int operUid, Grid_Info grid_Info, List<GridDetailBase> SelectOrderInfo, out bool hasAllProd, bool hasForcibePrint, int inPay)
        {

            hasAllProd = false;                                 //结帐的是否是该格子中的全部产品，影响到前台是否需要清空相应的格子

            int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样


            int shopId = grid_Info.SomeId;                      //商户ID
            if (grid_Info.GridType == (int)GridType.Custom)
            {
                shopId = SelectOrderInfo.FirstOrDefault().OrderBagInfo.ShopID;
            }
            List<int> ListOrderProductId = SelectOrderInfo.Select(p => p.OrderProductId).ToList();
            List<int> DonedOrderProudctId = new List<int>(ListOrderProductId);//能够正常结帐单的产品ID


            double Bill_Price = 0;                              //此帐单的总价格
            Shop curShop;                                       //当前商户
            Grid curGrid;                                       //当前格子

            SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
            SHOP_Bill sb = new SHOP_Bill();                     //用于向数库添加数据

            List<Tb_OrderBag> NeedMoveDataOrderList = new List<Tb_OrderBag>();//需要转移数据的定单包列表
            bool isNeedMoveData = false;
            bool isNeedOverOrderInfo = false;//是否需要完产品流程

            //初始信息
            sb.NeedDeliver = 1;                                 //是否需要配送   
            sb.Status = (int)ShopBillStatus.UnCheckOut;

            sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
            sbinfo.CreateTime = sb.CreateTime;//获取系统时间


            sbinfo.List_Detail = new List<Bill_Detail_Info>();


            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            {
                dataBase = new newSampleYPDBEntities();
                try
                {
                    curShop = dataBase.Shop.FirstOrDefault(p => p.ShopId == shopId);

                    #region 得到商户的帐单的顺序号

                    List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == shopId).ToList();
                    if (listShopBill.Count <= 0)
                    {
                        sb.BillOrderCode = 1;
                    }
                    else
                    {
                        sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                    }


                    //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                    sbinfo.BillOrderCode = sb.BillOrderCode;



                    #endregion

                    foreach (var orderProductId in ListOrderProductId)
                    {
                        if (true)
                        {
                            isNeedOverOrderInfo = true;
                            #region 帐单名细--每一层，就是产品（orderinfo）

                            decimal orderInfoPrice = 0;//此产品的真实价格

                            orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                            if (oi.status == (int)OrderInfoStatus.Completed)
                            {
                                dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
                            }

                            #region 加载数据库
                            if (!oi.Tb_ProductReference.IsLoaded)
                            {
                                oi.Tb_ProductReference.Load();
                            }
                            if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                            {
                                oi.Tb_Product.tb_CostTypeReference.Load();
                            }
                            if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                            {
                                oi.Tb_Product.Tb_PorductCategoryReference.Load();
                            }
                            if (!curShop.Shop_Product_Price.IsLoaded)
                            {
                                curShop.Shop_Product_Price.Load();
                            }
                            if (!oi.photoInfo.IsLoaded)
                            {
                                oi.photoInfo.Load();
                            }
                            if (!oi.Tb_OrderBagReference.IsLoaded)
                            {
                                oi.Tb_OrderBagReference.Load();
                            }
                            string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                            #endregion

                            Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                            Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                            Bill_Detail_Id++;
                            dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                            orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                            ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                            #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                            #region //对帐户金额的操作
                            ShopBlanceCrushRecord br;
                            switch (curShop.CheckOutType)
                            {
                                case 0://预付款用户
                                case 2://现结用户
                                case 5://先结
                                    #region


                                    curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }


                                    if (curShop.Balance < (decimal)orderInfoPrice)
                                    {
                                        //如果余额不足，就判断是否有权限可打印此帐单
                                        if (hasForcibePrint)//可以强打
                                        {
                                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                                            curShop.Balance -= (decimal)orderInfoPrice;
                                            //向商户帐户记录表添加记录
                                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                            dataBase.AddToShopBlanceCrushRecord(br);
                                        }
                                        else
                                        {
                                            oi.status = (int)OrderInfoStatus.WaitPay;
                                            curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                            isNeedOverOrderInfo = false;
                                            DonedOrderProudctId.Remove(oi.OrderProductId);
                                        }
                                    }
                                    else
                                    {

                                        bd.IsCheckOut = true;
                                        curShop.Balance -= (decimal)orderInfoPrice;

                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        dataBase.AddToShopBlanceCrushRecord(br);
                                    }

                                    //检查是否需要报警
                                    if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                    #endregion
                                    break;
                                case 1://信用额度用户
                                case 3://结帐日用户
                                case 4://结单日与信用额度用户
                                case 6://代收款
                                    #region
                                    curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }
                                    curShop.Balance -= (decimal)orderInfoPrice;

                                    if (curShop.CheckOutType == 1)//信用额度用户
                                    {
                                        if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                        }
                                    }
                                    else
                                    {
                                        int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                        if (days > 0 && days < curShop.AlarmDays)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                        }
                                    }

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    #endregion
                                    break;
                                default:
                                    break;
                            }

                            #endregion

                            if (isNeedOverOrderInfo)
                            {
                                bool result = _wflBll.OverCurTech(curTechId, operUid, oi, dataBase, out isNeedMoveData);

                                if (!result)
                                {
                                    throw new CustomMsgException(oi.OrderProductCode + "请检查此产品是否被暂停，如未被暂停，请重启程序！" + "(节点:" + curTechId.ToString() + "操作员:" + operUid.ToString());
                                }
                                else
                                {
                                    if (isNeedMoveData)
                                    {
                                        NeedMoveDataOrderList.Add(oi.Tb_OrderBag);
                                    }

                                    #region//在此修改相应的业绩记录
                                    double orderArea = -1;
                                    List<New_EmployeePerformance> emList = dataBase.New_EmployeePerformance.Where(e => e.OrderproductId == oi.OrderProductId).ToList();
                                    foreach (var em in emList)
                                    {
                                        if (orderArea == -1)
                                        {
                                            orderArea = dbinfo.ListDetail_Detail.Where(bddt => bddt.Type == (int)Bill_Detail_Detail_Type.NeedStatArea).Sum(bddt => bddt.Area);
                                        }
                                        if (em != null)
                                        {
                                            em.OrderCount = orderInfoPrice;
                                            em.Status = (int)OrderInfoStatus.Completed;
                                            em.OrderConpletedTime = oi.CompleteTime;
                                            em.OrderArea = orderArea;
                                        }
                                    }
                                    #endregion

                                    sb.Bill_Detail.Add(bd);

                                    dbinfo.BillDetailId = Bill_Detail_Id;
                                    sbinfo.List_Detail.Add(dbinfo);
                                    Bill_Detail_Id++;
                                    Bill_Price += (double)orderInfoPrice;
                                }
                            }

                            #endregion

                            #endregion
                        }
                    }
                    //添加运费项目
                    if (inPay > 0)
                    {
                        #region 收费项目
                        Bill_Detail bd = new Bill_Detail() { OiRemark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName };
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                        Bill_Detail_Id++;

                        bd.Bill_Detail_Detail.Add(new Bill_Detail_Detail()
                        {
                            Area = 0,
                            Count = inPay,
                            DetailName = "运费",
                            Num = 1,
                            Spec = "",
                            Type = 0,
                            UnitPrice = inPay
                        });

                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);

                        sb.Bill_Detail.Add(bd);

                        dbinfo.BillDetailId = Bill_Detail_Id;
                        sbinfo.List_Detail.Add(dbinfo);
                        Bill_Detail_Id++;
                        Bill_Price += (double)inPay;

                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                                #region
                                //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)inPay)//默认都是强大
                                {
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    curShop.Balance -= (decimal)inPay;
                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)inPay;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户 
                                #region
                                //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)inPay;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "运费:" + inPay + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }
                        #endregion 收费项目
                    }


                    #region 清除相应的格子信息

                    curGrid = dataBase.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);
                    if (!curGrid.GridRecord.IsLoaded)
                    {
                        curGrid.GridRecord.Load();
                    }
                    List<GridRecord> listRecord = curGrid.GridRecord.ToList();
                    foreach (var oId in DonedOrderProudctId)
                    {
                        GridRecord result = listRecord.Find(delegate(GridRecord gr)
                        {
                            if (gr.SomeId == oId)
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        });
                        if (result != null)
                        {
                            dataBase.DeleteObject(result);
                        }
                    }

                    if (listRecord.Count == DonedOrderProudctId.Count)
                    {
                        curGrid.Status = (int)GridStatus.useAble;
                        curGrid.SomeId = 0;
                        hasAllProd = true;
                    }
                    #endregion

                    //记录帐单信息            

                    sb.Shop = curShop;
                    ////curShop = dataBase.Shop.FirstOrDefault(p => p.ShopId == shopId);
                    sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                    sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                    sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                    //sbinfo.BillCount = Bill_Price;
                    sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                    if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                    {
                        if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                        {
                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                        }
                        else
                        {
                            sb.Status = (int)ShopBillStatus.CheckedOut;
                        }
                        sb.ShopBalance = curShop.Balance ?? 0;
                        dataBase.AddToSHOP_Bill(sb);

                        dataBase.SaveChanges();

                        ts.Complete();
                    }
                    else
                    {
                        sbinfo = null;
                        sb = null;
                    }


                    try
                    {
                        ////转移数据到历史记录表中,并删除相应的旧数据
                        //if (NeedMoveDataOrderList.Count > 0)
                        //{
                        //    Thread thMoveHistoryTable = new Thread(new ParameterizedThreadStart(ThMoveData));
                        //    thMoveHistoryTable.Start(NeedMoveDataOrderList);

                        //    statPhotoEffectAreaDelegate dlStat = new statPhotoEffectAreaDelegate(OrderInfoStatDAL.StatPhotoEffectArea);
                        //    dlStat.BeginInvoke(ListOrderProductId, null, null);
                        //}
                    }
                    catch (Exception ex)
                    {
                        WriteLogForCheck.WriteLogFile("在统计拼板面积或是移动历史数据时出错：" + ex.Message);
                    }
                    if (sbinfo != null)
                    {
                        sbinfo.BillId = sb.BillId;
                        sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                    }
                    return sbinfo;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 去掉msdtc事务后的分堆逻辑处理
        /// </summary>
        /// <param name="curTechId"></param>
        /// <param name="operUid"></param>
        /// <param name="grid_Info"></param>
        /// <param name="SelectOrderInfo"></param>
        /// <param name="hasAllProd"></param>
        /// <param name="hasForcibePrint"></param>
        /// <param name="inPay"></param>
        /// <returns></returns>
        public SHOP_Bill_Info NewOrderComplete(int curTechId, int operUid, Grid_Info grid_Info, List<OverOrderView> SelectOrderInfo, out bool hasAllProd, bool hasForcibePrint, int inPay)
        {

            hasAllProd = false;                                 //结帐的是否是该格子中的全部产品，影响到前台是否需要清空相应的格子

            int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样


            int shopId = grid_Info.SomeId;                      //商户ID
            if (grid_Info.GridType == (int)GridType.Custom)
            {
                shopId = SelectOrderInfo.FirstOrDefault().OrderBagInfo.ShopID;
            }
            List<int> ListOrderProductId = SelectOrderInfo.Select(p => p.OrderProductId).ToList();
            List<int> DonedOrderProudctId = new List<int>(ListOrderProductId);//能够正常结帐单的产品ID


            double Bill_Price = 0;                              //此帐单的总价格
            Shop curShop;                                       //当前商户
            Grid curGrid = null;                                       //当前格子

            SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
            SHOP_Bill sb = new SHOP_Bill();                     //用于向数库添加数据

            List<Tb_OrderBag> NeedMoveDataOrderList = new List<Tb_OrderBag>();//需要转移数据的定单包列表
            bool isNeedMoveData = false;
            bool isNeedOverOrderInfo = false;//是否需要完产品流程

            //初始信息
            sb.NeedDeliver = 1;                                 //是否需要配送   
            sb.Status = (int)ShopBillStatus.UnCheckOut;

            sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
            sbinfo.CreateTime = sb.CreateTime;//获取系统时间


            sbinfo.List_Detail = new List<Bill_Detail_Info>();


            //TransactionOptions options = new TransactionOptions();
            //options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            //using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            //{
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                if (db.Connection.State != System.Data.ConnectionState.Open)
                {
                    db.Connection.Open();
                }

                using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    try
                    {

                        curShop = db.Shop.FirstOrDefault(p => p.ShopId == shopId);
                        SalesmanBalance salesmanBalance = null;
                        salesmanBalance = db.SalesmanBalance.FirstOrDefault(s => s.SalesmanName == curShop.Salesman);

                        string CheckType = "";
                        switch (curShop.CheckOutType)
                        {
                            case 0:
                                CheckType = "预付款";
                                break;
                            case 1:
                                CheckType = "信用额度";

                                break;
                            case 2:
                                CheckType = "现结";
                                break;
                            case 3:
                                CheckType = "结账日期";

                                break;
                            case 4:
                                CheckType = "结账日期与信用额度";

                                break;
                            case 5:
                                CheckType = "先结";
                                break;
                            case 6:
                                CheckType = "代收";
                                break;
                            default:
                                break;
                        }
                        sbinfo.CheckType = CheckType;
                        #region 得到商户的帐单的顺序号

                        List<SHOP_Bill> listShopBill = db.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == shopId).ToList();
                        if (listShopBill.Count <= 0)
                        {
                            sb.BillOrderCode = 1;
                        }
                        else
                        {
                            sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                        }


                        //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                        sbinfo.BillOrderCode = sb.BillOrderCode;



                        #endregion

                        foreach (var orderProductId in ListOrderProductId.Distinct())
                        {
                            if (true)
                            {
                                isNeedOverOrderInfo = true;
                                #region 帐单名细--每一层，就是产品（orderinfo）

                                decimal orderInfoPrice = 0;//此产品的真实价格

                                orderInfo oi = db.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                                if (oi.status == (int)OrderInfoStatus.Completed)
                                {
                                    db.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
                                }

                                #region 加载数据库
                                if (!oi.Tb_ProductReference.IsLoaded)
                                {
                                    oi.Tb_ProductReference.Load();
                                }
                                if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                                {
                                    oi.Tb_Product.tb_CostTypeReference.Load();
                                }
                                if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                                {
                                    oi.Tb_Product.Tb_PorductCategoryReference.Load();
                                }
                                if (!curShop.Shop_Product_Price.IsLoaded)
                                {
                                    curShop.Shop_Product_Price.Load();
                                }
                                if (!oi.photoInfo.IsLoaded)
                                {
                                    oi.photoInfo.Load();
                                }
                                if (!oi.Tb_OrderBagReference.IsLoaded)
                                {
                                    oi.Tb_OrderBagReference.Load();
                                }
                                if (oi.isCount == 1)//已经打印过账单的产品直接过滤掉
                                {
                                    continue;
                                }
                                string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                                #endregion
                                string productName = "";
                                int flagIndex = oi.OrderProductName.LastIndexOf("_");
                                if (flagIndex > 0)
                                {
                                    productName = oi.OrderProductName.Substring(0, flagIndex);


                                }
                                else
                                {
                                    productName = oi.OrderProductName;
                                }
                                Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = productName, CtmName = oi.CtmName, IsCheckOut = false };
                                Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                                Bill_Detail_Id++;
                                dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                                orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, db, bd);

                                ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                                #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                                #region //对帐户金额的操作
                                ShopBlanceCrushRecord br;
                                switch (curShop.CheckOutType)
                                {
                                    case 0://预付款用户
                                    case 2://现结用户
                                    case 5://先结
                                        #region
                                        curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                        if (curShop.OrderBalance < 0)
                                        {
                                            curShop.OrderBalance = 0;
                                        }


                                        if (curShop.Balance < (decimal)orderInfoPrice)
                                        {
                                            //curShop = db.Shop.FirstOrDefault(pt => pt.ShopId == shopId);
                                            //如果余额不足，就判断是否有权限可打印此帐单
                                            if (hasForcibePrint)//可以强打
                                            {
                                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                                // dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                                curShop.Balance -= (decimal)orderInfoPrice;
                                                //向商户帐户记录表添加记录
                                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                                db.AddToShopBlanceCrushRecord(br);

                                            }
                                            else
                                            {
                                                oi.status = (int)OrderInfoStatus.WaitPay;
                                                //dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                                curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                                isNeedOverOrderInfo = false;
                                                DonedOrderProudctId.Remove(oi.OrderProductId);
                                            }
                                        }
                                        else
                                        {

                                            bd.IsCheckOut = true;
                                            //dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                            curShop.Balance -= (decimal)orderInfoPrice;

                                            //向商户帐户记录表添加记录
                                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                            db.AddToShopBlanceCrushRecord(br);
                                        }
                                        if (salesmanBalance != null)//对业务员账户操作
                                        {
                                            //dataBase.Refresh(RefreshMode.StoreWins, salesmanBalance);
                                            salesmanBalance.Balance -= (decimal)orderInfoPrice;
                                        }
                                        //检查是否需要报警
                                        if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                        }
                                        #endregion
                                        break;
                                    case 1://信用额度用户
                                    case 3://结帐日用户
                                    case 4://结单日与信用额度用户
                                    case 6://代收款
                                        #region

                                        curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                        if (curShop.OrderBalance < 0)
                                        {
                                            curShop.OrderBalance = 0;
                                        }
                                        //dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                        curShop.Balance -= (decimal)orderInfoPrice;
                                        if (salesmanBalance != null)//对业务员账户操作
                                        {
                                            // dataBase.Refresh(RefreshMode.StoreWins, salesmanBalance);
                                            salesmanBalance.Balance -= (decimal)orderInfoPrice;
                                        }
                                        if (curShop.CheckOutType == 1)//信用额度用户
                                        {
                                            if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                            {
                                                BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);

                                            }
                                        }
                                        else
                                        {
                                            int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                            if (days > 0 && days < curShop.AlarmDays)
                                            {
                                                BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                            }
                                        }

                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        #endregion
                                        break;
                                    default:
                                        break;
                                }

                                #endregion

                                if (isNeedOverOrderInfo)
                                {

                                    bool result = _wflBll.OverCurTech(curTechId, operUid, oi, db, out isNeedMoveData);

                                    if (!result)
                                    {
                                        throw new CustomMsgException(oi.OrderProductCode + "请检查此产品是否被暂停，如未被暂停，请重启程序！" + "(节点:" + curTechId.ToString() + "操作员:" + operUid.ToString());
                                    }
                                    else
                                    {
                                        if (isNeedMoveData)
                                        {
                                            NeedMoveDataOrderList.Add(oi.Tb_OrderBag);
                                        }

                                        #region//在此修改相应的业绩记录
                                        double orderArea = -1;
                                        List<New_EmployeePerformance> emList = db.New_EmployeePerformance.Where(e => e.OrderproductId == oi.OrderProductId).ToList();
                                        foreach (var em in emList)
                                        {
                                            if (orderArea == -1)
                                            {
                                                if (!oi.Tb_ProductReference.IsLoaded)
                                                    oi.Tb_ProductReference.Load();
                                                if (!oi.Tb_Product.tb_ProductTypeReference.IsLoaded)
                                                {
                                                    oi.Tb_Product.tb_ProductTypeReference.Load();
                                                }

                                                Shop_Product_Price spp = db.Shop_Product_Price.FirstOrDefault(sp => sp.Shop.ShopId == curShop.ShopId && sp.Tb_Product.ProuctId == oi.Tb_Product.ProuctId);
                                                spp.tb_CostTypeReference.Load();
                                                if (spp.tb_CostType.CostTypeId == 1 || spp.tb_CostType.CostTypeId == 4)
                                                {
                                                    //orderArea=
                                                    if (oi.Tb_Product.tb_ProductType.ProductTypeCode == 5 || oi.Tb_Product.tb_ProductType.ProductTypeCode == 6)
                                                    {
                                                        orderArea = oi.productNum * (oi.photoInfo.Sum(ph => (double)ph.TotalNum) * oi.Tb_Product.Width * oi.Tb_Product.Height * 2.54 * 2.54 / 10000);
                                                    }
                                                    else
                                                    {
                                                        orderArea = oi.photoInfo.Sum(ph => ph.Height * ph.Width * 2.54 * 2.54 / 10000);
                                                    }
                                                }
                                                else
                                                {
                                                    orderArea = dbinfo.ListDetail_Detail.Where(bddt => bddt.Type == (int)Bill_Detail_Detail_Type.NeedStatArea).Sum(bddt => bddt.Area);
                                                }
                                            }
                                            if (em != null)
                                            {
                                                em.OrderCount = orderInfoPrice;
                                                em.Status = (int)OrderInfoStatus.Completed;
                                                em.OrderConpletedTime = oi.CompleteTime;
                                                em.OrderArea = orderArea;
                                                em.ProductPhotoNum = Convert.ToInt32(oi.productNum * (oi.photoInfo.Sum(ph => ph.TotalNum)));
                                            }
                                        }
                                        #endregion

                                        sb.Bill_Detail.Add(bd);

                                        dbinfo.BillDetailId = Bill_Detail_Id;
                                        sbinfo.List_Detail.Add(dbinfo);
                                        Bill_Detail_Id++;
                                        Bill_Price += (double)orderInfoPrice;
                                    }
                                }

                                #endregion

                                #endregion
                            }
                        }
                        //添加运费项目
                        if (inPay > 0)
                        {
                            #region 收费项目
                            Bill_Detail bd = new Bill_Detail() { OiRemark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName, IsCheckOut = false };
                            Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName };
                            dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                            Bill_Detail_Id++;

                            bd.Bill_Detail_Detail.Add(new Bill_Detail_Detail()
                            {
                                Area = 0,
                                Count = inPay,
                                DetailName = "运费",
                                Num = 1,
                                Spec = "",
                                Type = 0,
                                UnitPrice = inPay
                            });

                            ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);

                            sb.Bill_Detail.Add(bd);

                            dbinfo.BillDetailId = Bill_Detail_Id;
                            sbinfo.List_Detail.Add(dbinfo);
                            Bill_Detail_Id++;
                            Bill_Price += (double)inPay;

                            ShopBlanceCrushRecord br;
                            switch (curShop.CheckOutType)
                            {
                                case 0://预付款用户
                                case 2://现结用户
                                    #region
                                    //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }


                                    if (curShop.Balance < (decimal)inPay)//默认都是强大
                                    {
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        curShop.Balance -= (decimal)inPay;
                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                    }
                                    else
                                    {

                                        bd.IsCheckOut = true;
                                        curShop.Balance -= (decimal)inPay;

                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                    }

                                    //检查是否需要报警
                                    if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                    }
                                    #endregion
                                    break;
                                case 1://信用额度用户
                                case 3://结帐日用户
                                case 4://结单日与信用额度用户 
                                    #region
                                    //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }
                                    curShop.Balance -= (decimal)inPay;

                                    if (curShop.CheckOutType == 1)//信用额度用户
                                    {
                                        if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);

                                        }
                                    }
                                    else
                                    {
                                        int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                        if (days > 0 && days < curShop.AlarmDays)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "运费:" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                        }
                                    }

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    db.AddToShopBlanceCrushRecord(br);
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    #endregion
                                    break;
                                default:
                                    break;
                            }
                            #endregion 收费项目
                        }


                        #region 清除相应的格子信息

                        curGrid = db.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);
                        if (!curGrid.GridRecord.IsLoaded)
                        {
                            curGrid.GridRecord.Load();
                        }
                        List<GridRecord> listRecord = curGrid.GridRecord.ToList();
                        foreach (var oId in DonedOrderProudctId)
                        {
                            GridRecord result = listRecord.Find(delegate(GridRecord gr)
                            {
                                if (gr.SomeId == oId)
                                {
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            });
                            if (result != null)
                            {
                                db.DeleteObject(result);
                            }
                        }

                        if (listRecord.Count == DonedOrderProudctId.Count)
                        {
                            curGrid.Status = (int)GridStatus.useAble;
                            curGrid.SomeId = 0;
                            hasAllProd = true;
                        }
                        #endregion

                        //记录帐单信息            

                        sb.Shop = curShop;
                        sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom, Remark = curShop.Remark };
                        sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                        //sbinfo.BillCount = Bill_Price;
                        sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                        {
                            if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                            {
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                            }
                            else
                            {
                                sb.Status = (int)ShopBillStatus.CheckedOut;
                            }
                            sb.ShopBalance = curShop.Balance ?? 0;
                            db.AddToSHOP_Bill(sb);

                            db.SaveChanges();
                            sbinfo.BillId = sb.BillId;
                            //db.AcceptAllChanges();
                            tran.Commit();
                        }
                        else
                        {
                            sbinfo = null;
                            sb = null;
                            tran.Rollback();
                        }
                        if (sbinfo != null)
                        {
                            sbinfo.BillId = sb.BillId;
                            sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                        }
                        return sbinfo;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 带业务员算账模式
        /// </summary>
        /// <param name="curTechId"></param>
        /// <param name="operUid"></param>
        /// <param name="grid_Info"></param>
        /// <param name="SelectOrderInfo"></param>
        /// <param name="hasAllProd"></param>
        /// <param name="hasForcibePrint"></param>
        /// <param name="inPay"></param>
        /// <returns></returns>
        public SHOP_Bill_Info OrderCompleteWithSealman(int curTechId, int operUid, Grid_Info grid_Info, List<GridDetailBase> SelectOrderInfo, out bool hasAllProd, bool hasForcibePrint, int inPay)
        {

            hasAllProd = false;                                 //结帐的是否是该格子中的全部产品，影响到前台是否需要清空相应的格子

            int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样


            int shopId = grid_Info.SomeId;                      //商户ID
            if (grid_Info.GridType == (int)GridType.Custom)
            {
                shopId = SelectOrderInfo.FirstOrDefault().OrderBagInfo.ShopID;
            }
            List<int> ListOrderProductId = SelectOrderInfo.Select(p => p.OrderProductId).ToList();
            List<int> DonedOrderProudctId = new List<int>(ListOrderProductId);//能够正常结帐单的产品ID


            double Bill_Price = 0;                              //此帐单的总价格
            Shop curShop;                                       //当前商户
            Grid curGrid = null;                                       //当前格子

            SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
            SHOP_Bill sb = new SHOP_Bill();                     //用于向数库添加数据

            List<Tb_OrderBag> NeedMoveDataOrderList = new List<Tb_OrderBag>();//需要转移数据的定单包列表
            bool isNeedMoveData = false;
            bool isNeedOverOrderInfo = false;//是否需要完产品流程

            //初始信息
            sb.NeedDeliver = 1;                                 //是否需要配送   
            sb.Status = (int)ShopBillStatus.UnCheckOut;

            sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
            sbinfo.CreateTime = sb.CreateTime;//获取系统时间


            sbinfo.List_Detail = new List<Bill_Detail_Info>();


            //TransactionOptions options = new TransactionOptions();
            //options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            //using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            //{
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                if (db.Connection.State != System.Data.ConnectionState.Open)
                {
                    db.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);

                try
                {

                    curShop = db.Shop.FirstOrDefault(p => p.ShopId == shopId);

                    #region 得到商户的帐单的顺序号

                    List<SHOP_Bill> listShopBill = db.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == shopId).ToList();
                    if (listShopBill.Count <= 0)
                    {
                        sb.BillOrderCode = 1;
                    }
                    else
                    {
                        sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                    }


                    //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                    sbinfo.BillOrderCode = sb.BillOrderCode;



                    #endregion

                    foreach (var orderProductId in ListOrderProductId)
                    {
                        if (true)
                        {
                            isNeedOverOrderInfo = true;
                            #region 帐单名细--每一层，就是产品（orderinfo）

                            decimal orderInfoPrice = 0;//此产品的真实价格

                            orderInfo oi = db.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                            if (oi.status == (int)OrderInfoStatus.Completed)
                            {
                                db.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
                            }

                            #region 加载数据库
                            if (!oi.Tb_ProductReference.IsLoaded)
                            {
                                oi.Tb_ProductReference.Load();
                            }
                            if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                            {
                                oi.Tb_Product.tb_CostTypeReference.Load();
                            }
                            if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                            {
                                oi.Tb_Product.Tb_PorductCategoryReference.Load();
                            }
                            if (!curShop.Shop_Product_Price.IsLoaded)
                            {
                                curShop.Shop_Product_Price.Load();
                            }
                            if (!oi.photoInfo.IsLoaded)
                            {
                                oi.photoInfo.Load();
                            }
                            if (!oi.Tb_OrderBagReference.IsLoaded)
                            {
                                oi.Tb_OrderBagReference.Load();
                            }
                            string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                            #endregion

                            Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                            Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                            Bill_Detail_Id++;
                            dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                            orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, db, bd);

                            ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                            #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                            #region //对帐户金额的操作
                            ShopBlanceCrushRecord br;
                            switch (curShop.CheckOutType)
                            {
                                case 0://预付款用户
                                case 2://现结用户
                                case 5://先结
                                    #region
                                    curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }


                                    if (curShop.Balance < (decimal)orderInfoPrice)
                                    {
                                        //如果余额不足，就判断是否有权限可打印此帐单
                                        if (hasForcibePrint)//可以强打
                                        {
                                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                                            curShop.Balance -= (decimal)orderInfoPrice;
                                            //向商户帐户记录表添加记录
                                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                            db.AddToShopBlanceCrushRecord(br);

                                        }
                                        else
                                        {
                                            oi.status = (int)OrderInfoStatus.WaitPay;
                                            curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                            isNeedOverOrderInfo = false;
                                            DonedOrderProudctId.Remove(oi.OrderProductId);
                                        }
                                    }
                                    else
                                    {

                                        bd.IsCheckOut = true;
                                        curShop.Balance -= (decimal)orderInfoPrice;

                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                    }

                                    //检查是否需要报警
                                    if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                    }
                                    #endregion
                                    break;
                                case 1://信用额度用户
                                case 3://结帐日用户
                                case 4://结单日与信用额度用户
                                case 6://代收款
                                    #region
                                    curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }
                                    curShop.Balance -= (decimal)orderInfoPrice;

                                    if (curShop.CheckOutType == 1)//信用额度用户
                                    {
                                        if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);

                                        }
                                    }
                                    else
                                    {
                                        int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                        if (days > 0 && days < curShop.AlarmDays)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                        }
                                    }

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    db.AddToShopBlanceCrushRecord(br);
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    #endregion
                                    break;
                                default:
                                    break;
                            }

                            #endregion

                            if (isNeedOverOrderInfo)
                            {
                                bool result = _wflBll.OverCurTech(curTechId, operUid, oi, db, out isNeedMoveData);

                                if (!result)
                                {
                                    throw new CustomMsgException(oi.OrderProductCode + "请检查此产品是否被暂停，如未被暂停，请重启程序！" + "(节点:" + curTechId.ToString() + "操作员:" + operUid.ToString());
                                }
                                else
                                {
                                    if (isNeedMoveData)
                                    {
                                        NeedMoveDataOrderList.Add(oi.Tb_OrderBag);
                                    }

                                    #region//在此修改相应的业绩记录
                                    double orderArea = -1;
                                    List<New_EmployeePerformance> emList = db.New_EmployeePerformance.Where(e => e.OrderproductId == oi.OrderProductId).ToList();
                                    foreach (var em in emList)
                                    {
                                        if (orderArea == -1)
                                        {
                                            orderArea = dbinfo.ListDetail_Detail.Where(bddt => bddt.Type == (int)Bill_Detail_Detail_Type.NeedStatArea).Sum(bddt => bddt.Area);
                                        }
                                        if (em != null)
                                        {
                                            em.OrderCount = orderInfoPrice;
                                            em.Status = (int)OrderInfoStatus.Completed;
                                            em.OrderConpletedTime = oi.CompleteTime;
                                            em.OrderArea = orderArea;
                                        }
                                    }
                                    #endregion

                                    sb.Bill_Detail.Add(bd);

                                    dbinfo.BillDetailId = Bill_Detail_Id;
                                    sbinfo.List_Detail.Add(dbinfo);
                                    Bill_Detail_Id++;
                                    Bill_Price += (double)orderInfoPrice;
                                }
                            }

                            #endregion

                            #endregion
                        }
                    }
                    //添加运费项目
                    if (inPay > 0)
                    {
                        #region 收费项目
                        Bill_Detail bd = new Bill_Detail() { OiRemark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName };
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                        Bill_Detail_Id++;

                        bd.Bill_Detail_Detail.Add(new Bill_Detail_Detail()
                        {
                            Area = 0,
                            Count = inPay,
                            DetailName = "运费",
                            Num = 1,
                            Spec = "",
                            Type = 0,
                            UnitPrice = inPay
                        });

                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);

                        sb.Bill_Detail.Add(bd);

                        dbinfo.BillDetailId = Bill_Detail_Id;
                        sbinfo.List_Detail.Add(dbinfo);
                        Bill_Detail_Id++;
                        Bill_Price += (double)inPay;

                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                                #region
                                //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)inPay)//默认都是强大
                                {
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    curShop.Balance -= (decimal)inPay;
                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    db.AddToShopBlanceCrushRecord(br);
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)inPay;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    db.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户 
                                #region
                                //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)inPay;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "运费:" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                db.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }
                        #endregion 收费项目
                    }


                    #region 清除相应的格子信息

                    curGrid = db.Grid.FirstOrDefault(p => p.GridId == grid_Info.GridId);
                    if (!curGrid.GridRecord.IsLoaded)
                    {
                        curGrid.GridRecord.Load();
                    }
                    List<GridRecord> listRecord = curGrid.GridRecord.ToList();
                    foreach (var oId in DonedOrderProudctId)
                    {
                        GridRecord result = listRecord.Find(delegate(GridRecord gr)
                        {
                            if (gr.SomeId == oId)
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        });
                        if (result != null)
                        {
                            db.DeleteObject(result);
                        }
                    }

                    if (listRecord.Count == DonedOrderProudctId.Count)
                    {
                        curGrid.Status = (int)GridStatus.useAble;
                        curGrid.SomeId = 0;
                        hasAllProd = true;
                    }
                    #endregion

                    //记录帐单信息            

                    sb.Shop = curShop;
                    sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                    sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                    sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                    //sbinfo.BillCount = Bill_Price;
                    sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                    if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                    {
                        if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                        {
                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                        }
                        else
                        {
                            sb.Status = (int)ShopBillStatus.CheckedOut;
                        }
                        sb.ShopBalance = curShop.Balance ?? 0;
                        db.AddToSHOP_Bill(sb);

                        db.SaveChanges();
                        tran.Commit();
                    }
                    else
                    {
                        sbinfo = null;
                        sb = null;
                        tran.Rollback();
                    }
                    if (sbinfo != null)
                    {
                        sbinfo.BillId = sb.BillId;
                        sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                    }
                    return sbinfo;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 检查该产品有没有扣账
        /// </summary>
        /// <param name="enty"></param>
        /// <param name="orderproductid"></param>
        /// <returns></returns>
        public bool CheckRecordExist(newSampleYPDBEntities enty, int orderproductid)
        {
            string opidstr = orderproductid.ToString();
            bool flag = false;
            ShopBlanceCrushRecord crushRecord = enty.ShopBlanceCrushRecord.FirstOrDefault(s => s.Remark.Contains(opidstr));
            if (crushRecord != null)
            {
                flag = true;
            }
            return flag;
        }
        /// <summary>
        /// 将Bill_Detail转换为要打印的信息
        /// </summary>
        /// <param name="bd"></param>
        /// <param name="curShop"></param>
        /// <param name="bdInfo"></param>
        private void ConvertOrderDetailaToViewModel(Bill_Detail bd, Shop curShop, Bill_Detail_Info bdInfo)
        {
            foreach (var bdd in bd.Bill_Detail_Detail.ToList())
            {
                bdInfo.ListDetail_Detail.Add(new Bill_Detail_Detail_Info()
                {
                    Area = bdd.Area,
                    Count = bdd.Count,
                    DetailName = bdd.DetailName,
                    Num = bdd.Num,
                    Spec = bdd.Spec,
                    Type = bdd.Type ?? 0,
                    UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0,
                    Bill_Detail_DetailId = bdInfo.BillDetailId,
                    DetailRemark = bdd.DetailRemark
                });
            }
        }


        /// <summary>
        /// 得到某产品的真实价格
        /// </summary>
        /// <param name="orderProductId">产品ID</param>
        /// <param name="curShop">当前商户</param>
        /// <param name="shopProductPriceList">该商户的产品价格表</param>
        /// <param name="Bill_Detail_Detail_Id">生成帐单的ID</param>
        /// <param name="dbinfo">如果需要打印报表时的数据信息</param>
        /// <returns></returns>
        //public Bill_Detail GetOrderProductBillInfo(int orderProductId, Shop curShop, List<Shop_Product_Price> shopProductPriceList, ref int Bill_Detail_Detail_Id, out Bill_Detail_Info dbinfo)
        //{
        //    double orderInfoPrice = 0;//此产品的真实价格

        //    orderInfo oi = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == orderProductId);

        //    if (oi.status == (int)OrderInfoStatus.Completed)
        //    {
        //        dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
        //    }


        //    #region 加载数据库
        //    if (!oi.Tb_ProductReference.IsLoaded)
        //    {
        //        oi.Tb_ProductReference.Load();
        //    }
        //    if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
        //    {
        //        oi.Tb_Product.tb_CostTypeReference.Load();
        //    }
        //    if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
        //    {
        //        oi.Tb_Product.Tb_PorductCategoryReference.Load();
        //    }
        //    if (!curShop.Shop_Product_Price.IsLoaded)
        //    {
        //        curShop.Shop_Product_Price.Load();
        //    }
        //    if (!oi.photoInfo.IsLoaded)
        //    {
        //        oi.photoInfo.Load();
        //    }


        //    #endregion

        //    Shop_Product_Price spp = shopProductPriceList.FirstOrDefault(sp => sp.ProductId == oi.Tb_Product.ProuctId);

        //    Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName };
        //    dbinfo = new Bill_Detail_Info() { Remark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName };

        //    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();

        //    Bill_Detail_Detail bdd;
        //    Bill_Detail_Detail_Info bddinfo = null;


        //    #region 价格明细---第二层，即产品里面的名细，如规格，单价等

        //    switch (oi.Tb_Product.tb_CostType.CostTypeId)
        //    {
        //        case 1: //按单价计价
        //            #region
        //            bdd = new Bill_Detail_Detail();
        //            if (spp == null)
        //            {
        //                bdd.UnitPrice = 0;
        //            }
        //            else
        //            {
        //                bdd.UnitPrice = (double)spp.UnitPrice;
        //            }

        //            bdd.DetailName = oi.Tb_Product.Tb_PorductCategory.ProductCategoryName;
        //            //bdd.Spec = oi.Tb_Product.ProductName;
        //            bdd.Spec = oi.Tb_Product.ProductName + oi.Tb_Product.Width + "×" + oi.Tb_Product.Width;
        //            bdd.Num = oi.productNum;
        //            bdd.Count = bdd.UnitPrice * bdd.Num;
        //            orderInfoPrice += bdd.Count;
        //            bdd.Area = 0;
        //            bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //            bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            bd.Bill_Detail_Detail.Add(bdd);

        //            bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            Bill_Detail_Detail_Id++;
        //            dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            dbinfo.ListDetail_Detail.Add(bddinfo);

        //            //再计算附加页热的明细
        //            if (oi.photoInfo.Count > oi.Tb_Product.PageNum)
        //            {
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    bdd.UnitPrice = (double)spp.AppendPrice;//附加页的价格
        //                }
        //                bdd.DetailName = "附加页";
        //                //bdd.Spec = oi.Tb_Product.ProductName;
        //                bdd.Spec = oi.Tb_Product.ProductName + oi.Tb_Product.Width + "×" + oi.Tb_Product.Height + "附加页";
        //                bdd.Num = oi.photoInfo.Count - oi.Tb_Product.PageNum;
        //                bdd.Count = bdd.Num * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                bdd.Area = 0;
        //                bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;

        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };


        //                bd.Bill_Detail_Detail.Add(bdd);

        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;

        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //            }

        //            break;
        //            #endregion

        //        case 2:  //按平米计价,就要按此定单下的照片的规格分类
        //            #region

        //            bool isOneToMore = false;
        //            int pInum = 0;//实际照片总数
        //            if (oi.photoInfo.Count == 1)
        //            {
        //                photoInfo pi = oi.photoInfo.FirstOrDefault();
        //                if (pi != null)
        //                {
        //                    pInum = ((int)pi.TotalNum) * oi.productNum;
        //                    if (pInum > 1)
        //                    {
        //                        //证明是那种一低多张并且委外直出的产品（即没有经过分配打印节点）
        //                        isOneToMore = true;
        //                    }
        //                }
        //            }
        //            foreach (var item in oi.photoInfo.GroupBy(pi => (pi.Width.ToString("0.0") + "×" + pi.Height.ToString("0.0") + " in" + "(" + (pi.Width * 2.54).ToString("0.0") + "×" + (pi.Height * 2.54).ToString("0.0") + " cm" + ")")))
        //            {
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    //bdd.UnitPrice = spp.AreaPrice;///*
        //                }
        //                bdd.DetailName = "数码输出";
        //                bdd.Spec = item.Key;

        //                if (isOneToMore)
        //                {
        //                    bdd.Num = pInum;
        //                }
        //                else
        //                {
        //                    bdd.Num = item.Count();
        //                }

        //                foreach (var pi in item)
        //                {
        //                    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //                }
        //                bdd.Count = bdd.Area * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;

        //                bd.Bill_Detail_Detail.Add(bdd);
        //                bdd.Type = (int)Bill_Detail_Detail_Type.NeedStatArea;
        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };



        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;
        //                if (dbinfo.ListDetail_Detail == null)
        //                {
        //                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //                }

        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //            }

        //            break;
        //            #endregion

        //        case 3://组合计价方式（即平米计价+产品单价）

        //            #region 面积
        //            foreach (var item in oi.photoInfo.GroupBy(pi => (pi.Width.ToString("0.0") + "×" + pi.Height.ToString("0.0") + " in" + "(" + (pi.Width * 2.54).ToString("0.0") + "×" + (pi.Height * 2.54).ToString("0.0") + " cm" + ")")))
        //            {
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    //bdd.UnitPrice = spp.AreaPrice;///*
        //                }
        //                bdd.DetailName = "数码输出";
        //                bdd.Spec = item.Key;
        //                bdd.Num = item.Count();
        //                foreach (var pi in item)
        //                {
        //                    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //                }
        //                bdd.Count = bdd.Area * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                bdd.Type = (int)Bill_Detail_Detail_Type.NeedStatArea;
        //                bd.Bill_Detail_Detail.Add(bdd);
        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;
        //                if (dbinfo.ListDetail_Detail == null)
        //                {
        //                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //                }
        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //            }
        //            #endregion

        //            #region 单价
        //            bdd = new Bill_Detail_Detail();
        //            if (spp == null)
        //            {
        //                bdd.UnitPrice = 0;
        //            }
        //            else
        //            {
        //                bdd.UnitPrice = (double)spp.UnitPrice;
        //            }

        //            bdd.DetailName = oi.Tb_Product.Tb_PorductCategory.ProductCategoryName;
        //            bdd.Spec = oi.Tb_Product.ProductName + oi.Tb_Product.Width + "×" + oi.Tb_Product.Height;
        //            bdd.Num = oi.productNum;
        //            bdd.Count = bdd.UnitPrice * bdd.Num;
        //            orderInfoPrice += bdd.Count;
        //            bdd.Area = 0;
        //            bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //            bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            bd.Bill_Detail_Detail.Add(bdd);

        //            bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            Bill_Detail_Detail_Id++;
        //            //dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            dbinfo.ListDetail_Detail.Add(bddinfo);
        //            #endregion

        //            #region //再计算附加页热的明细
        //            if (oi.PageNum > oi.Tb_Product.PageNum)
        //            {
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    bdd.UnitPrice = (double)spp.AppendPrice;//附加页的价格
        //                }
        //                bdd.DetailName = "附加页";
        //                //bdd.Spec = oi.Tb_Product.ProductName;
        //                bdd.Spec = oi.Tb_Product.ProductName + oi.Tb_Product.Width + "×" + oi.Tb_Product.Height + "附加页";
        //                bdd.Num = oi.PageNum - oi.Tb_Product.PageNum;
        //                bdd.Count = bdd.Num * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                bdd.Area = 0;
        //                bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };


        //                bd.Bill_Detail_Detail.Add(bdd);

        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;

        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //            }
        //            #endregion

        //            break;
        //        case 4://按照片张数计价
        //            #region

        //            var onePi = oi.photoInfo.FirstOrDefault();
        //            bdd = new Bill_Detail_Detail();
        //            if (spp == null)
        //            {
        //                bdd.UnitPrice = 0;
        //            }
        //            else
        //            {
        //                bdd.UnitPrice = (double)spp.UnitPrice;
        //            }
        //            bdd.DetailName = "单片输出";
        //            bdd.Spec = onePi.Width.ToString("0.0") + "*" + onePi.Height.ToString("0.0") + "(" + (onePi.Width * 2.54).ToString("0.0") + "*" + (onePi.Height * 2.54).ToString("0.0") + ")";
        //            bdd.Num = oi.photoInfo.Count;

        //            bdd.Area = onePi.Width * onePi.Height * 2.54 * 2.54 / 10000 * bdd.Num;//平方米

        //            bdd.Count = bdd.Num * bdd.UnitPrice;
        //            orderInfoPrice += bdd.Count;
        //            bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //            bd.Bill_Detail_Detail.Add(bdd);
        //            bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            Bill_Detail_Detail_Id++;
        //            if (dbinfo.ListDetail_Detail == null)
        //            {
        //                dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            }

        //            dbinfo.ListDetail_Detail.Add(bddinfo);

        //            break;
        //            #endregion

        //        case 5://冷裱、压痕等计价方式
        //        case 8://设计--按面积计价
        //            #region

        //            foreach (var item in oi.photoInfo.GroupBy(pi => (pi.Width.ToString("0.0") + "×" + pi.Height.ToString("0.0") + " in" + "(" + (pi.Width * 2.54).ToString("0.0") + "×" + (pi.Height * 2.54).ToString("0.0") + " cm" + ")")))
        //            {
        //                #region 输出照片面积
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    //bdd.UnitPrice = spp.AreaPrice;///*
        //                }
        //                bdd.DetailName = "数码输出";
        //                bdd.Spec = item.Key;
        //                bdd.Num = item.Count();
        //                foreach (var pi in item)
        //                {
        //                    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //                }
        //                bdd.Count = bdd.Area * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                bdd.Type = (int)Bill_Detail_Detail_Type.NeedStatArea;
        //                bd.Bill_Detail_Detail.Add(bdd);

        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };



        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;
        //                if (dbinfo.ListDetail_Detail == null)
        //                {
        //                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //                }

        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //                #endregion

        //                #region 冷裱、压痕的价格
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    bdd.UnitPrice = (double)spp.UnitPrice;//冷裱、压痕每平米价格
        //                }
        //                bdd.DetailName = oi.Tb_Product.Tb_PorductCategory.ProductCategoryName;
        //                bdd.Spec = oi.Tb_Product.ProductName;
        //                bdd.Num = item.Count();
        //                foreach (var pi in item)
        //                {
        //                    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //                }
        //                bdd.Count = bdd.Area * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                if (oi.Tb_Product.tb_CostType.CostTypeId == 8)//设计类
        //                {
        //                    bdd.Type = (int)Bill_Detail_Detail_Type.Design;
        //                    bdd.Spec = "设计";
        //                }
        //                else
        //                {
        //                    bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //                }

        //                bd.Bill_Detail_Detail.Add(bdd);

        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };



        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;
        //                if (dbinfo.ListDetail_Detail == null)
        //                {
        //                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //                }

        //                dbinfo.ListDetail_Detail.Add(bddinfo);

        //                #endregion
        //            }
        //            break;

        //            #endregion
        //        case 6://超常规直出，即超宽超长类直出
        //            #region
        //            foreach (var item in oi.photoInfo.GroupBy(pi => (pi.Width.ToString("0.0") + "×" + pi.Height.ToString("0.0") + " in" + "(" + (pi.Width * 2.54).ToString("0.0") + "×" + (pi.Height * 2.54).ToString("0.0") + " cm" + ")")))
        //            {
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    //bdd.UnitPrice = spp.AreaPrice;///*
        //                }
        //                bdd.DetailName = oi.Tb_Product.ProductName;
        //                bdd.Spec = item.Key;
        //                bdd.Num = item.Count();
        //                foreach (var pi in item)
        //                {
        //                    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //                }
        //                bdd.Count = bdd.Area * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                bdd.Type = (int)Bill_Detail_Detail_Type.NeedStatArea;
        //                bd.Bill_Detail_Detail.Add(bdd);

        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };



        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;
        //                if (dbinfo.ListDetail_Detail == null)
        //                {
        //                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //                }

        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //            }

        //            break;
        //            #endregion

        //        case 7://片按面积计价、设计按单张计价
        //            #region 片按面积计价
        //            foreach (var item in oi.photoInfo.GroupBy(pi => (pi.Width.ToString("0.0") + "×" + pi.Height.ToString("0.0") + " in" + "(" + (pi.Width * 2.54).ToString("0.0") + "×" + (pi.Height * 2.54).ToString("0.0") + " cm" + ")")))
        //            {
        //                bdd = new Bill_Detail_Detail();
        //                if (spp == null)
        //                {
        //                    bdd.UnitPrice = 0;
        //                }
        //                else
        //                {
        //                    //bdd.UnitPrice = spp.AreaPrice;///*
        //                }
        //                bdd.DetailName = "数码输出";
        //                bdd.Spec = item.Key;
        //                bdd.Num = item.Count();
        //                foreach (var pi in item)
        //                {
        //                    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //                }
        //                bdd.Count = bdd.Area * bdd.UnitPrice;
        //                orderInfoPrice += bdd.Count;
        //                bdd.Type = (int)Bill_Detail_Detail_Type.NeedStatArea;
        //                bd.Bill_Detail_Detail.Add(bdd);
        //                bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //                bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //                Bill_Detail_Detail_Id++;
        //                if (dbinfo.ListDetail_Detail == null)
        //                {
        //                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //                }
        //                dbinfo.ListDetail_Detail.Add(bddinfo);
        //            }
        //            #endregion

        //            #region 设计按单张计价费

        //            var onePiDesign = oi.photoInfo.FirstOrDefault();
        //            bdd = new Bill_Detail_Detail();
        //            if (spp == null)
        //            {
        //                bdd.UnitPrice = 0;
        //            }
        //            else
        //            {
        //                bdd.UnitPrice = (double)spp.UnitPrice;
        //            }
        //            bdd.DetailName = "设计";
        //            bdd.Spec = onePiDesign.Width.ToString("0.0") + "*" + onePiDesign.Height.ToString("0.0") + "(" + (onePiDesign.Width * 2.54).ToString("0.0") + "*" + (onePiDesign.Height * 2.54).ToString("0.0") + ")";
        //            bdd.Num = oi.photoInfo.Count;

        //            bdd.Area = onePiDesign.Width * onePiDesign.Height * 2.54 * 2.54 / 10000 * bdd.Num;//平方米

        //            bdd.Count = bdd.Num * bdd.UnitPrice;
        //            orderInfoPrice += bdd.Count;
        //            bdd.Type = (int)Bill_Detail_Detail_Type.Design;//设计类收费
        //            bd.Bill_Detail_Detail.Add(bdd);
        //            bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            Bill_Detail_Detail_Id++;
        //            if (dbinfo.ListDetail_Detail == null)
        //            {
        //                dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            }

        //            dbinfo.ListDetail_Detail.Add(bddinfo);


        //            #endregion
        //            break;
        //        case 10://片按单张计价、设计按单张计价
        //            #region 单张计价

        //            var onePi2 = oi.photoInfo.FirstOrDefault();
        //            bdd = new Bill_Detail_Detail();
        //            if (spp == null)
        //            {
        //                bdd.UnitPrice = 0;
        //            }
        //            else
        //            {
        //                bdd.UnitPrice = (double)spp.AppendPrice;
        //            }
        //            bdd.DetailName = "单片输出";
        //            bdd.Spec = onePi2.Width.ToString("0.0") + "*" + onePi2.Height.ToString("0.0") + "(" + (onePi2.Width * 2.54).ToString("0.0") + "*" + (onePi2.Height * 2.54).ToString("0.0") + ")";
        //            bdd.Num = oi.photoInfo.Count;

        //            bdd.Area = onePi2.Width * onePi2.Height * 2.54 * 2.54 / 10000 * bdd.Num;//平方米

        //            bdd.Count = bdd.Num * bdd.UnitPrice;
        //            orderInfoPrice += bdd.Count;
        //            bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //            bd.Bill_Detail_Detail.Add(bdd);
        //            bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            Bill_Detail_Detail_Id++;
        //            if (dbinfo.ListDetail_Detail == null)
        //            {
        //                dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            }

        //            dbinfo.ListDetail_Detail.Add(bddinfo);


        //            #endregion

        //            #region 设计的单片收费
        //            var onePi3 = oi.photoInfo.FirstOrDefault();
        //            bdd = new Bill_Detail_Detail();
        //            if (spp == null)
        //            {
        //                bdd.UnitPrice = 0;
        //            }
        //            else
        //            {
        //                bdd.UnitPrice = (double)spp.UnitPrice;
        //            }
        //            bdd.DetailName = "单片设计";
        //            bdd.Spec = onePi3.Width.ToString("0.0") + "*" + onePi3.Height.ToString("0.0") + "(" + (onePi3.Width * 2.54).ToString("0.0") + "*" + (onePi3.Height * 2.54).ToString("0.0") + ")";
        //            bdd.Num = oi.photoInfo.Count;

        //            bdd.Area = onePi3.Width * onePi3.Height * 2.54 * 2.54 / 10000 * bdd.Num;//平方米

        //            bdd.Count = bdd.Num * bdd.UnitPrice;
        //            orderInfoPrice += bdd.Count;
        //            bdd.Type = (int)Bill_Detail_Detail_Type.Design;
        //            bd.Bill_Detail_Detail.Add(bdd);
        //            bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            Bill_Detail_Detail_Id++;
        //            if (dbinfo.ListDetail_Detail == null)
        //            {
        //                dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            }

        //            dbinfo.ListDetail_Detail.Add(bddinfo);
        //            #endregion

        //            break;
        //        case 11://片按单张计价、设计按面积计价
        //            #region 单张计价，注释掉

        //            //onePi2 = oi.photoInfo.FirstOrDefault();
        //            //bdd = new Bill_Detail_Detail();
        //            //if (spp == null)
        //            //{
        //            //    bdd.UnitPrice = 0;
        //            //}
        //            //else
        //            //{
        //            //    bdd.UnitPrice = spp.AppendPrice;
        //            //}
        //            //bdd.DetailName = "单片输出";
        //            //bdd.Spec = onePi2.Width.ToString("0.0") + "*" + onePi2.Height.ToString("0.0") + "(" + (onePi2.Width * 2.54).ToString("0.0") + "*" + (onePi2.Height * 2.54).ToString("0.0") + ")";
        //            //bdd.Num = oi.photoInfo.Count;

        //            //bdd.Area = onePi2.Width * onePi2.Height * 2.54 * 2.54 / 10000 * bdd.Num;//平方米

        //            //bdd.Count = bdd.Num * bdd.UnitPrice;
        //            //orderInfoPrice = bdd.Count;
        //            //bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //            //bd.Bill_Detail_Detail.Add(bdd);
        //            //bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };

        //            //bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            //Bill_Detail_Detail_Id++;
        //            //if (dbinfo.ListDetail_Detail == null)
        //            //{
        //            //    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            //}

        //            //dbinfo.ListDetail_Detail.Add(bddinfo);


        //            //#endregion

        //            //#region 冷裱、压痕的价格
        //            //bdd = new Bill_Detail_Detail();
        //            //if (spp == null)
        //            //{
        //            //    bdd.UnitPrice = 0;
        //            //}
        //            //else
        //            //{
        //            //    bdd.UnitPrice = spp.UnitPrice;//冷裱、压痕每平米价格
        //            //}
        //            //bdd.DetailName = oi.Tb_Product.Tb_PorductCategory.ProductCategoryName;
        //            //bdd.Spec = oi.Tb_Product.ProductName;
        //            //bdd.Num = item.Count();
        //            //foreach (var pi in item)
        //            //{
        //            //    bdd.Area += pi.Width * pi.Height * 2.54 * 2.54 / 10000;//平方米
        //            //}
        //            //bdd.Count = bdd.Area * bdd.UnitPrice;
        //            //orderInfoPrice += bdd.Count;
        //            //if (oi.Tb_Product.tb_CostType.CostTypeId == 8)//设计类
        //            //{
        //            //    bdd.Type = (int)Bill_Detail_Detail_Type.Design;
        //            //}
        //            //else
        //            //{
        //            //    bdd.Type = (int)Bill_Detail_Detail_Type.UnNeedStatArea;
        //            //}

        //            //bd.Bill_Detail_Detail.Add(bdd);

        //            //bddinfo = new Bill_Detail_Detail_Info() { Type = (int)bdd.Type, UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0, DetailName = bdd.DetailName, Spec = bdd.Spec, Num = bdd.Num, Area = bdd.Area, Count = bdd.Count };



        //            //bddinfo.Bill_Detail_DetailId = Bill_Detail_Detail_Id;
        //            //Bill_Detail_Detail_Id++;
        //            //if (dbinfo.ListDetail_Detail == null)
        //            //{
        //            //    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
        //            //}

        //            //dbinfo.ListDetail_Detail.Add(bddinfo);

        //            #endregion
        //            break;
        //    }

        //    #endregion

        //    return bd;
        //}




        private ShopBlanceCrushRecord GetShopLastCrushRecord(int shopId)
        {
            using (newSampleYPDBEntities DB = new newSampleYPDBEntities())
            {
                return DB.ShopBlanceCrushRecord.Where(b => b.Shop.ShopId == shopId && (b.Operation == 1 || b.Operation == 2)).OrderByDescending(b => b.CrushTime).FirstOrDefault();
            }
        }

        //public void ThMoveData(object p)
        //{
        //    MoveDataParmater parm = (MoveDataParmater)p;
        //    MoveDataToHistroyTable(parm.listSource, parm.dataSource);
        //}

        public void ThMoveData(object p)
        {
            List<Tb_OrderBag> listSource = (List<Tb_OrderBag>)p;
            foreach (var ob in listSource)
            {
                DataMaintenance.MoveHistoryData(ob.OrderBagId);
            }
        }

        private struct MoveDataParmater
        {
            public List<Tb_OrderBag> listSource;
            public newSampleYPDBEntities dataSource;
        }




        /// <summary>
        /// 商户信息
        /// </summary>
        /// <returns></returns>
        public List<Shop_Info> GetAllShop()
        {
            List<Shop_Info> listShopInfo = new List<Shop_Info>();
            List<Shop> listShop = dataBase.Shop.Where(sh => sh.Status == 1).ToList();
            foreach (Shop shop in listShop)
            {
                Shop_Info shopinfo = new Shop_Info() { ShopId = shop.ShopId, ShopName = shop.shopName, Area = shop.Area };
                listShopInfo.Add(shopinfo);
            }
            return listShopInfo.OrderBy(p => p.ShopName).ToList(); ;
        }

        public List<OrderView> GetView(int inShopId, DateTime inStartTime, DateTime inEndTime, int inGridType)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                List<OrderView> rtnView = new List<OrderView>();
                List<Tb_OrderBag> orderBagList = GetAllBag(inShopId, inStartTime, inEndTime, inGridType, dataBase);
                if (orderBagList == null || orderBagList.Count < 1)
                {
                    return new List<OrderView>();
                }
                else
                {
                    foreach (Tb_OrderBag bag in orderBagList)
                    {

                        if (!bag.orderInfo.IsLoaded)
                        {
                            bag.orderInfo.Load();
                        }
                        int orderStatus = (int)OrderInfoStatus.Doing;
                        List<orderInfo> orderinfoList = bag.orderInfo.ToList().Where(oi => oi.OrderType == (int)OrderInfoType.Normal && oi.status == orderStatus).ToList();
                        foreach (orderInfo info in orderinfoList)
                        {
                            if (info.status == (int)OrderInfoStatus.Doing)
                            {
                                OrderView view = new OrderView();
                                if (!bag.ShopReference.IsLoaded)
                                {
                                    bag.ShopReference.Load();
                                }
                                view.Orderbag = new Tb_OrderBag_Info() { FetchTime = bag.FetchTime, BagCode = bag.BagCode, BagName = bag.BagName, OrderTime = bag.OrderTime, OrderBagId = bag.OrderBagId, Remark = bag.Remark, ShopID = bag.Shop.ShopId, ShopName = bag.Shop.shopName };

                                view.Orderinfo = new OrderInfo_Info() { OrderBagId = info.Tb_OrderBag.OrderBagId, CtmName = info.CtmName, Height = info.Height, Width = info.Width, OrderProductId = info.OrderProductId, OrderProductName = info.OrderProductName, PageNum = info.PageNum, ProductNum = info.productNum, Remark = info.Remark, Status = info.status };
                                int intDong = (int)OrderFlowListStatus.Useable;
                                int intDong1 = (int)OrderFlowListStatus.UseableAccept;
                                int intPause = (int)OrderFlowListStatus.UnProduct;
                                if (!info.WorkOrderFlowList.IsLoaded)
                                {
                                    info.WorkOrderFlowList.Load();
                                }
                                else
                                {
                                    info.WorkOrderFlowList.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                                }
                                WorkOrderFlowList workflow = info.WorkOrderFlowList.Where(p => p.Status == intDong || p.Status == intDong1).FirstOrDefault();
                                if (workflow == null)
                                {
                                    view.Tech = new Tb_Tech_Info() { TechName = "暂停生产" };
                                }
                                else
                                {
                                    if (!workflow.tb_TechReference.IsLoaded)
                                    {
                                        workflow.tb_TechReference.Load();
                                    }
                                    view.Tech = new Tb_Tech_Info() { TechId = workflow.tb_Tech.TechId, TechName = workflow.tb_Tech.TechName };

                                }
                                rtnView.Add(view);
                            }
                        }

                    }
                }
                return rtnView;



            }


        }
        public List<OrderView> GetTastView(int inTechID, int inGridType)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                List<OrderView> rtnView = new List<OrderView>();




                int orderStatus = (int)OrderInfoStatus.Doing;
                List<orderInfo> orderinfoList = dataBase.orderInfo.Where(oi => oi.OrderType == (int)OrderInfoType.Normal && oi.status == orderStatus && oi.WorkOrderFlowList.Count(wf => wf.tb_Tech.TechId == inTechID && wf.Status == 1) > 0).ToList();
                foreach (orderInfo info in orderinfoList)
                {
                    if (info.status == (int)OrderInfoStatus.Doing)
                    {
                        OrderView view = new OrderView();
                        if (dataBase.GridRecord.Count(c => c.SomeId == info.OrderProductId) > 0)
                        {
                            continue;
                        }
                        if (!info.Tb_OrderBagReference.IsLoaded)
                        {
                            info.Tb_OrderBagReference.Load();
                        }
                        Tb_OrderBag bag = info.Tb_OrderBag;
                        if (!bag.ShopReference.IsLoaded)
                        {
                            bag.ShopReference.Load();
                        }
                        view.Orderbag = new Tb_OrderBag_Info() { FetchTime = bag.FetchTime, BagCode = bag.BagCode, BagName = bag.BagName, OrderTime = bag.OrderTime, OrderBagId = bag.OrderBagId, Remark = bag.Remark, ShopID = bag.Shop.ShopId, ShopName = bag.Shop.shopName };

                        view.Orderinfo = new OrderInfo_Info() { OrderBagId = info.Tb_OrderBag.OrderBagId, CtmName = info.CtmName, Height = info.Height, Width = info.Width, OrderProductId = info.OrderProductId, OrderProductName = info.OrderProductName, PageNum = info.PageNum, ProductNum = info.productNum, Remark = info.Remark, Status = info.status };
                        int intDong = (int)OrderFlowListStatus.Useable;
                        int intDong1 = (int)OrderFlowListStatus.UseableAccept;
                        int intPause = (int)OrderFlowListStatus.UnProduct;
                        if (!info.WorkOrderFlowList.IsLoaded)
                        {
                            info.WorkOrderFlowList.Load();
                        }
                        else
                        {
                            info.WorkOrderFlowList.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                        }
                        WorkOrderFlowList workflow = info.WorkOrderFlowList.Where(p => p.Status == intDong || p.Status == intDong1).FirstOrDefault();
                        if (workflow == null)
                        {
                            view.Tech = new Tb_Tech_Info() { TechName = "暂停生产" };
                        }
                        else
                        {
                            if (!workflow.tb_TechReference.IsLoaded)
                            {
                                workflow.tb_TechReference.Load();
                            }
                            view.Tech = new Tb_Tech_Info() { TechId = workflow.tb_Tech.TechId, TechName = workflow.tb_Tech.TechName };

                        }
                        rtnView.Add(view);
                    }
                }



                return rtnView;



            }


        }

        public OutProcessShop_Info GetOutShopInfo(int inshopId)
        {
            OutProcessShop shop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == inshopId);
            return new OutProcessShop_Info() { OutShopId = shop.OutShopId, OutShopName = shop.OutShopName, EmailAddress = shop.EmailAddress };



        }
        public string GetOutShopEmail(int inOutShopid)
        {
            return dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == inOutShopid).EmailAddress;
        }

        public List<Tb_OrderBag> GetAllBag(int inShopId, DateTime inStartTime, DateTime inEndTime, int inGridType, newSampleYPDBEntities dataBase)
        {
            int ordeBagStatus = (int)OrderBagStatus.Doing;
            int orderBagStatus_Complete = (int)OrderBagStatus.Completed;
            if (inGridType == (int)GridType.Shop)
            {
                if (inStartTime != DateTime.MinValue && inEndTime != DateTime.MinValue)
                {
                    if (inShopId != 0)
                    {
                        return
                            dataBase.Tb_OrderBag.Where(
                                p =>
                                p.Shop.ShopId == inShopId && p.OrderTime > inStartTime && p.OrderTime < inEndTime &&
                                p.Status != orderBagStatus_Complete).ToList();
                    }
                    else
                    {
                        return
                            dataBase.Tb_OrderBag.Where(
                                p =>
                                p.OrderTime > inStartTime && p.OrderTime < inEndTime &&
                                p.Status != orderBagStatus_Complete).ToList();

                    }
                }
                else
                {
                    return
                        dataBase.Tb_OrderBag.Where(p => p.Shop.ShopId == inShopId && p.Status != orderBagStatus_Complete)
                            .ToList();
                }
            }
            else
            {
                return dataBase.Tb_OrderBag.Where(p => p.OrderBagId == inShopId).ToList();

            }
        }
        /// <summary>
        /// 转出产品
        /// </summary>
        /// <returns></returns>
        public string GetZhuanString(string inBarCode)
        {
            orderInfo oi = dataBase.orderInfo.Where(p => p.OrderProductCode == inBarCode).FirstOrDefault();
            if (oi == null)
            {
                return null;
            }
            else
            {
                string mark = oi.Remark;
                int length = mark.Length;
                int index = -1;
                //int index2 = mark.IndexOf("留");
                List<string> listFlag = new List<string> {"转","留","淋" };

                foreach (string str in listFlag)
                {
                    index = mark.IndexOf(str);
                    if (index != -1)
                    {
                        break;
                    }
 
                }

                if (index == -1)
                {
                    return null;
                }
                else
                {
                    int leftIndex = length - index;
                    if (leftIndex >= 5)
                    {
                        leftIndex = 5;
                    }
                    return mark.Substring(index, leftIndex);
                }
            }
        }
        /*
        public List<OrderInfo_Info> ReceiveReBarCode(string inStrBarCode, out Shop_Info outShop)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<OrderInfo_Info> rtnList = new List<OrderInfo_Info>();
                Shop_Info shopInfo = new Shop_Info();

                //orderInfo product = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductCode == inStrBarCode);

                orderInfo product = db.orderInfo.FirstOrDefault(p => p.OrderProductCode == inStrBarCode);
                if (product == null)//生产表中无记录
                {
                    //orderInfo_BK productBk = dataBase.orderInfo_BK.FirstOrDefault(p => p.OrderProductCode == inStrBarCode);
                    orderInfo_BK productBk = db.orderInfo_BK.FirstOrDefault(p => p.OrderProductCode == inStrBarCode);

                    if (productBk == null)
                    {
                        outShop = shopInfo;
                        return new List<OrderInfo_Info>();
                    }
                    else// 账单表里找记录,
                    {
                        //dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, productBk);
                        //Bill_Detail detail = dataBase.Bill_Detail.FirstOrDefault(p => p.OrderInfoCode == inStrBarCode);
                        Bill_Detail detail = db.Bill_Detail.FirstOrDefault(p => p.OrderInfoCode == inStrBarCode);
                        if (detail == null)
                        {
                            outShop = shopInfo;
                            return new List<OrderInfo_Info>();
                        }
                        else
                        {
                            //dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, detail);
                            detail.SHOP_BillReference.Load();
                            SHOP_Bill bill = detail.SHOP_Bill;
                            bill.ShopReference.Load();
                            Shop shop = bill.Shop;
                            shopInfo = new Shop_Info() { Address = shop.address, Area = shop.Area, ShopId = shop.ShopId, ShopName = shop.shopName, ShopKeeper = shopInfo.ShopKeeper, Tel1 = shopInfo.Tel1 };
                            bill.Bill_Detail.Load();
                            List<Bill_Detail> detailList = detail.SHOP_Bill.Bill_Detail.ToList();
                            foreach (Bill_Detail each in detailList)
                            {
                                //orderInfo_BK orderBK = dataBase.orderInfo_BK.FirstOrDefault(p => p.OrderProductCode == each.OrderInfoCode);
                                orderInfo_BK orderBK = db.orderInfo_BK.FirstOrDefault(p => p.OrderProductCode == each.OrderInfoCode);
                                if (orderBK == null)
                                {
                                    //orderInfo order = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductCode == each.OrderInfoCode);
                                    orderInfo order = db.orderInfo.FirstOrDefault(p => p.OrderProductCode == each.OrderInfoCode);
                                    OrderInfo_Info info = new OrderInfo_Info() { CompleteTime = order.CompleteTime, CtmName = order.CtmName, Height = order.Height, OrderProductCode = order.OrderProductCode, OrderProductName = order.OrderProductName, PageNum = order.PageNum, OrderProductId = order.ParentProductId, ProductNum = order.productNum, Remark = order.Remark, Width = order.Width };
                                    rtnList.Add(info);
                                }
                                else
                                {
                                    OrderInfo_Info info = new OrderInfo_Info() { CompleteTime = orderBK.CompleteTime, CtmName = orderBK.CtmName, Height = orderBK.Height, OrderProductCode = orderBK.OrderProductCode, OrderProductName = orderBK.OrderProductName, PageNum = orderBK.PageNum, OrderProductId = orderBK.ParentProductId, ProductNum = orderBK.productNum, Remark = orderBK.Remark, Width = orderBK.Width };
                                    rtnList.Add(info);
                                }
                            }
                            outShop = shopInfo;
                            return rtnList;
                        }
                    }
                }
                else//在orderiNfo表中找到了记录
                {
                    //dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, product);
                    Shop shop = new Shop();
                    if (product.status == (int)OrderInfoStatus.Completed)//从帐单中去找
                    {
                        //Bill_Detail detail = dataBase.Bill_Detail.FirstOrDefault(p => p.OrderInfoCode == inStrBarCode);
                        Bill_Detail detail = db.Bill_Detail.FirstOrDefault(p => p.OrderInfoCode == inStrBarCode);
                        if (detail == null)
                        {
                            outShop = shopInfo;
                            return new List<OrderInfo_Info>();
                        }
                        else
                        {
                            //dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, detail);
                            detail.SHOP_BillReference.Load();
                            SHOP_Bill bill = detail.SHOP_Bill;
                            bill.ShopReference.Load();
                            shop = bill.Shop;
                            shopInfo = new Shop_Info() { Address = shop.address, Area = shop.Area, ShopId = shop.ShopId, ShopName = shop.shopName, ShopKeeper = shopInfo.ShopKeeper, Tel1 = shopInfo.Tel1 };
                            bill.Bill_Detail.Load();
                            List<Bill_Detail> detailList = detail.SHOP_Bill.Bill_Detail.ToList();
                            foreach (Bill_Detail each in detailList)
                            {
                                //orderInfo order = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductCode == each.OrderInfoCode);
                                orderInfo order = db.orderInfo.FirstOrDefault(p => p.OrderProductCode == each.OrderInfoCode);
                                OrderInfo_Info info = new OrderInfo_Info() { CompleteTime = order.CompleteTime, CtmName = order.CtmName, Height = order.Height, OrderProductCode = order.OrderProductCode, OrderProductName = order.OrderProductName, PageNum = order.PageNum, OrderProductId = order.ParentProductId, ProductNum = order.productNum, Remark = order.Remark, Width = order.Width };
                                rtnList.Add(info);
                            }
                            outShop = shopInfo;
                            return rtnList;
                        }
                    }
                    else//去格子中找所有产品来复检
                    {
                        //GridRecord record = dataBase.GridRecord.FirstOrDefault(p => p.SomeId == product.OrderProductId);
                        GridRecord record = db.GridRecord.FirstOrDefault(p => p.SomeId == product.OrderProductId);
                        if (record == null)
                        {
                            outShop = shopInfo;
                            return null;
                        }
                        product.Tb_OrderBagReference.Load();
                        Tb_OrderBag orderBag = product.Tb_OrderBag;
                        orderBag.ShopReference.Load();
                        shop = orderBag.Shop;
                        shopInfo = new Shop_Info() { Address = shop.address, Area = shop.Area, ShopId = shop.ShopId, ShopName = shop.shopName, ShopKeeper = shopInfo.ShopKeeper, Tel1 = shopInfo.Tel1 };
                        record.GridReference.Load();
                        Grid grid = record.Grid;
                        grid.GridRecord.Load();
                        List<GridRecord> recordList = grid.GridRecord.ToList();
                        foreach (GridRecord each in recordList)
                        {
                            //orderInfo oi = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == each.SomeId);
                            orderInfo oi = db.orderInfo.FirstOrDefault(p => p.OrderProductId == each.SomeId);
                            OrderInfo_Info info = new OrderInfo_Info() { CompleteTime = oi.CompleteTime, CtmName = oi.CtmName, Height = oi.Height, OrderProductCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, PageNum = oi.PageNum, OrderProductId = oi.ParentProductId, ProductNum = oi.productNum, Remark = oi.Remark, Width = oi.Width };
                            rtnList.Add(info);
                        }
                        outShop = shopInfo;
                        return rtnList;
                    }
                }
            }
        }
        */
        private int ConvertBarCodeToId(string strBarCode)
        {
            if (strBarCode.Length == 10)
            {
                try
                {
                    return Convert.ToInt32(strBarCode.Substring(1));
                }
                catch (Exception)
                {
                    return 0;
                }

            }
            return 0;
        }

        public List<OrderInfo_Info> ReceiveReBarCode(string inStrBarCode, out Shop_Info outShop)
        {
            outShop = null;
            List<OrderInfo_Info> resultList = null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                //先从格子记录中去查找
                int orderProductId = ConvertBarCodeToId(inStrBarCode);
                if (orderProductId > 0)
                {
                    GridRecord gr = db.GridRecord.FirstOrDefault(g => g.SomeId == orderProductId);
                    if (gr == null)// 不在格子中
                    {
                        #region 不在格子中
                        Bill_Detail bd = db.Bill_Detail.FirstOrDefault(b => b.OrderInfoCode == inStrBarCode);
                        if (db != null)//在帐单中
                        {
                            if (!bd.SHOP_BillReference.IsLoaded)
                            {
                                bd.SHOP_BillReference.Load();
                            }
                            if (!bd.SHOP_Bill.Bill_Detail.IsLoaded)
                            {
                                bd.SHOP_Bill.Bill_Detail.Load();
                            }

                            foreach (var orderBarCode in bd.SHOP_Bill.Bill_Detail.ToList().Select(b => b.OrderInfoCode).ToList())
                            {
                                int tempOrderProductId = ConvertBarCodeToId(orderBarCode);
                                if (tempOrderProductId != 0)
                                {
                                    orderInfo_BK oi = db.orderInfo_BK.FirstOrDefault(o => o.OrderProductId == tempOrderProductId);

                                    if (oi != null)
                                    {
                                        #region 在备份数据表中
                                        if (outShop == null)
                                        {
                                            if (!oi.Tb_OrderBag_BKReference.IsLoaded)
                                            {
                                                oi.Tb_OrderBag_BKReference.Load();
                                            }
                                            if (!oi.Tb_OrderBag_BK.ShopReference.IsLoaded)
                                            {
                                                oi.Tb_OrderBag_BK.ShopReference.Load();
                                            }
                                            outShop = new Shop_Info() { Address = oi.Tb_OrderBag_BK.Shop.address, Area = oi.Tb_OrderBag_BK.Shop.Area, ShopId = oi.Tb_OrderBag_BK.Shop.ShopId, ShopName = oi.Tb_OrderBag_BK.Shop.shopName, ShopKeeper = oi.Tb_OrderBag_BK.Shop.shopKeeper, Tel1 = oi.Tb_OrderBag_BK.Shop.Tel1 };
                                        }

                                        if (resultList == null)
                                        {
                                            resultList = new List<OrderInfo_Info>();
                                        }
                                        resultList.Add(new OrderInfo_Info()
                                        {
                                            CompleteTime = oi.CompleteTime,
                                            CtmName = oi.CtmName,
                                            Height = oi.Height,
                                            OrderProductCode = oi.OrderProductCode,
                                            OrderProductName = oi.OrderProductName,
                                            PageNum = oi.PageNum,
                                            OrderProductId = oi.ParentProductId,
                                            ProductNum = oi.productNum,
                                            Remark = oi.Remark,
                                            Width = oi.Width
                                        });
                                        #endregion
                                    }
                                    else//产品完成了，但是还没有移动到备份数据库中
                                    {
                                        #region 产品完成，但还未移动到备份数据表中
                                        orderInfo oiT = db.orderInfo.FirstOrDefault(o => o.OrderProductId == tempOrderProductId);

                                        if (oiT != null)
                                        {
                                            if (outShop == null)
                                            {
                                                if (!oiT.Tb_OrderBagReference.IsLoaded)
                                                {
                                                    oiT.Tb_OrderBagReference.Load();
                                                }
                                                if (!oiT.Tb_OrderBag.ShopReference.IsLoaded)
                                                {
                                                    oiT.Tb_OrderBag.ShopReference.Load();
                                                }
                                                outShop = new Shop_Info() { Address = oiT.Tb_OrderBag.Shop.address, Area = oiT.Tb_OrderBag.Shop.Area, ShopId = oiT.Tb_OrderBag.Shop.ShopId, ShopName = oiT.Tb_OrderBag.Shop.shopName, ShopKeeper = oiT.Tb_OrderBag.Shop.shopKeeper, Tel1 = oiT.Tb_OrderBag.Shop.Tel1 };
                                            }

                                            if (resultList == null)
                                            {
                                                resultList = new List<OrderInfo_Info>();
                                            }

                                            resultList.Add(new OrderInfo_Info()
                                            {
                                                CompleteTime = oiT.CompleteTime,
                                                CtmName = oiT.CtmName,
                                                Height = oiT.Height,
                                                OrderProductCode = oiT.OrderProductCode,
                                                OrderProductName = oiT.OrderProductName,
                                                PageNum = oiT.PageNum,
                                                OrderProductId = oiT.ParentProductId,
                                                ProductNum = oiT.productNum,
                                                Remark = oiT.Remark,
                                                Width = oiT.Width
                                            });
                                        }
                                        #endregion
                                    }
                                }
                            }

                        }
                        else//即不在格子中也不在帐单中
                        {
                            return null;
                        }

                        #endregion
                    }
                    else//说明还在格子中，未打印帐单
                    {
                        #region 说明还在格子中，未打印帐单
                        if (!gr.GridReference.IsLoaded)
                        {
                            gr.GridReference.Load();
                        }
                        if (!gr.Grid.GridRecord.IsLoaded)
                        {
                            gr.Grid.GridRecord.Load();
                        }

                        List<int> orderProductIdListInGrid = gr.Grid.GridRecord.Select(g => g.SomeId).ToList();

                        foreach (var orderId in orderProductIdListInGrid)
                        {
                            orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderId);

                            if (oi != null)
                            {
                                if (outShop == null)
                                {
                                    if (!oi.Tb_OrderBagReference.IsLoaded)
                                    {
                                        oi.Tb_OrderBagReference.Load();
                                    }
                                    if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                                    {
                                        oi.Tb_OrderBag.ShopReference.Load();
                                    }
                                    outShop = new Shop_Info() { Address = oi.Tb_OrderBag.Shop.address, Area = oi.Tb_OrderBag.Shop.Area, ShopId = oi.Tb_OrderBag.Shop.ShopId, ShopName = oi.Tb_OrderBag.Shop.shopName, ShopKeeper = oi.Tb_OrderBag.Shop.shopKeeper, Tel1 = oi.Tb_OrderBag.Shop.Tel1 };
                                }

                                if (resultList == null)
                                {
                                    resultList = new List<OrderInfo_Info>();
                                }

                                resultList.Add(new OrderInfo_Info()
                                {
                                    CompleteTime = oi.CompleteTime,
                                    CtmName = oi.CtmName,
                                    Height = oi.Height,
                                    OrderProductCode = oi.OrderProductCode,
                                    OrderProductName = oi.OrderProductName,
                                    PageNum = oi.PageNum,
                                    OrderProductId = oi.ParentProductId,
                                    ProductNum = oi.productNum,
                                    Remark = oi.Remark,
                                    Width = oi.Width
                                });
                            }
                        }

                        #endregion
                    }

                }
            }

            return resultList;
        }


        public int GetProductOrderProductByShopId(int inShopId)
        {
            string recordSql = "select orderInfo.OrderProductId as OrderProductId from Tb_OrderBag inner join orderInfo on Tb_OrderBag.OrderBagId=orderInfo.Tb_OrderBag.OrderBagId and orderInfo.status= " + (int)OrderInfoStatus.Doing + " and  orderInfo.OrderType=" + (int)OrderInfoType.Normal + " and Tb_OrderBag.Shop.shopID=" + inShopId;

            ObjectQuery<DbDataRecord> dr = dataBase.CreateQuery<DbDataRecord>(recordSql);
            return dr.Count();

        }
        public int GetProductOrderProductByShopId(int inShopId, int intype)
        {
            string recordSql = "";

            int intDprint = (int)OrderInfoProductType.NeedDesignPrint;
            int intprint = (int)OrderInfoProductType.NoNeedDesignPrint;
            int intDproduct = (int)OrderInfoProductType.NeedDesignProduct;
            int intproduct = (int)OrderInfoProductType.NoNeedDesignProduct;
            int intNoPhoto = (int)OrderInfoProductType.NoPhotoProduct;
            if (intype == 0)
            {
                recordSql = "select orderInfo.OrderProductId as OrderProductId from Tb_OrderBag inner join orderInfo on Tb_OrderBag.OrderBagId=orderInfo.Tb_OrderBag.OrderBagId and orderInfo.status= " + (int)OrderInfoStatus.Doing + " and  orderInfo.OrderType=" + (int)OrderInfoType.Normal + " and Tb_OrderBag.Shop.shopID=" + inShopId;
            }
            else if (intype == 1)//输出
            {
                recordSql = "select orderInfo.OrderProductId as OrderProductId from Tb_OrderBag inner join orderInfo on Tb_OrderBag.OrderBagId=orderInfo.Tb_OrderBag.OrderBagId and orderInfo.status= " + (int)OrderInfoStatus.Doing + " and  orderInfo.OrderType=" + (int)OrderInfoType.Normal + " and Tb_OrderBag.Shop.shopID=" + inShopId + " and orderInfo.ProductType in {" + intDprint + "," + intprint + "}";

            }
            else
            {
                recordSql = "select orderInfo.OrderProductId as OrderProductId from Tb_OrderBag inner join orderInfo on Tb_OrderBag.OrderBagId=orderInfo.Tb_OrderBag.OrderBagId and orderInfo.status= " + (int)OrderInfoStatus.Doing + " and  orderInfo.OrderType=" + (int)OrderInfoType.Normal + " and Tb_OrderBag.Shop.shopID=" + inShopId + " and orderInfo.ProductType in {" + intDproduct + "," + intproduct + "," + intNoPhoto + "}";

            }

            ObjectQuery<DbDataRecord> dr = dataBase.CreateQuery<DbDataRecord>(recordSql);
            return dr.Count();

        }
        public int GetProductOrderProductFromByShopId(int inShopId)
        {
            string recordSql = "select GridRecord.SomeId as SomeId from Grid inner join GridRecord on GridRecord.Grid.GridId=Grid.GridId and Grid.SomeId=" + inShopId;

            ObjectQuery<DbDataRecord> dr = dataBase.CreateQuery<DbDataRecord>(recordSql);
            return dr.Count();

        }
        public int GetProductOrderProductFromByShopId(int inShopId, int intType)
        {
            //string recordSql = "";

            //    recordSql =
            //        "select value it  from Grid  as it inner join GridRecord on GridRecord.Grid.GridId=it.GridId and it.SomeId=" +
            //        inShopId;

            //    List<Grid> dr = dataBase.CreateQuery<Grid>(recordSql).ToList();
            List<GridRecord> listGridRecord = dataBase.GridRecord.Where(p => p.Grid.SomeId == inShopId).ToList();
            int rtnInt = 0;
            foreach (GridRecord query in listGridRecord)
            {
                if (intType == 1)
                {
                    orderInfo onfo = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == query.SomeId && p.Tb_Product.ProductName == "直出");
                    if (onfo != null)
                    {
                        rtnInt++;
                    }
                }
                else if (intType == 2)
                {
                    orderInfo onfo = dataBase.orderInfo.FirstOrDefault(p => p.OrderProductId == query.SomeId && p.Tb_Product.ProductName != "直出");
                    if (onfo != null)
                    {
                        rtnInt++;
                    }
                }
                else
                {
                    rtnInt++;
                }
            }

            return rtnInt;

        }

        /// <summary>
        /// 保存委外账单
        /// </summary>
        /// <param name="inListOrderProduct"></param>
        /// <param name="inUserID"></param>
        /// <param name="inOutShopId"></param>
        /// <returns></returns>
        public bool RecordOutShopBill(List<OverOrderView> inListOrderProduct, int inUserID, int inOutShopId, out int billID, out int Index)
        {
            try
            {
                using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
                {
                    OutShop_Bill bill = new OutShop_Bill();

                    DateTime timeNow = CommonMethodDAL.GetServerTime(); //获取系统时间

                    bill.CreateTime = timeNow;
                    bill.CreateUser = inUserID;

                    List<OutShop_Bill> listShopBill =
                        dataBase.OutShop_Bill.Where(
                            s =>
                            s.CreateTime.Month == timeNow.Month && s.CreateTime.Year == timeNow.Year &&
                            s.OutProcessShop.OutShopId == inOutShopId).ToList();
                    if (listShopBill.Count <= 0)
                    {
                        bill.BillOrderCode = 1;
                    }
                    else
                    {
                        bill.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                    }
                    OutProcessShop outShop = dataBase.OutProcessShop.FirstOrDefault(p => p.OutShopId == inOutShopId);
                    bill.OutProcessShop = outShop;
                    outShop.Tb_OutShop_ProductCategory.Load();
                    bill.PayStatus = (int)OutProcessPayStatus.UnPay;
                    bill.ProductSratus = (int)OutProcessProductStatus.Outting;
                    //List<OutShopBillDetail> listBillDetail=new List<OutShopBillDetail>();
                    decimal summed = 0;
                    foreach (OverOrderView list in inListOrderProduct)
                    {
                        decimal unitPrice = 0;
                        Tb_OutShop_ProductCategory category =
                            outShop.Tb_OutShop_ProductCategory.FirstOrDefault(p => p.ProductId == list.Productid);
                        if (category == null)
                        {
                            unitPrice = 0;
                        }
                        else
                        {
                            unitPrice = category.UnitPrice;
                        }
                        //处理有制作工艺的产品流程


                        OutShopBillDetail detail = new OutShopBillDetail();
                        detail.CtmName = list.CtmName;
                        detail.Num = list.ProductNum;
                        detail.OrderProductCode = list.OrderProductCode;
                        detail.OrderProductName = list.OrderProductName;
                        detail.PayStatus = (int)OutProcessPayStatus.UnPay;
                        detail.ProductStatus = (int)OutProcessProductStatus.Outting;
                        detail.ProductName = list.ProductName;
                        detail.OutShop_Bill = bill;
                        detail.Spc = list.Size;
                        detail.UnitPrice = unitPrice;
                        summed += list.ProductNum * unitPrice;
                        //  listBillDetail.Add(detail);
                    }
                    bill.Summed = summed;
                    bill.SummedRecive = 0;
                    bill.SummedPay = 0;


                    dataBase.AddToOutShop_Bill(bill);
                    dataBase.SaveChanges();
                    billID = bill.BillID;
                    Index = bill.BillOrderCode;
                }
            }
            catch (Exception ex)
            {
                billID = 0;
                Index = 0;
                return false;
            }


            return true;
        }

        //public List<string> 
        /// <summary>
        /// 获取发货信息
        /// </summary>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public Shop_DistributionInfo_Info Get_DistributionInfoInfoByShopId(int inShopId)
        {
            shop_DistributionInfo shopDistributionInfo =
                dataBase.shop_DistributionInfo.FirstOrDefault(p => p.ShopId == inShopId);
            Shop_DistributionInfo_Info info = new Shop_DistributionInfo_Info();
            if (shopDistributionInfo != null)
            {
                info.BusTimetable = shopDistributionInfo.BusTimetable;
                info.ConsigneeName = shopDistributionInfo.ConsigneeName;
                info.ConsigneeTelePhone = shopDistributionInfo.ConsigneeTelePhone;
                info.DistributionAddress = shopDistributionInfo.DistributionAddress;
                info.DistributionMode = shopDistributionInfo.DistributionMode;
                info.FarePayer = shopDistributionInfo.FarePayer;
                info.ReMark = shopDistributionInfo.ReMark;
            }

            return info;
        }

    }
}
